Find longest sequence of 1's in binary representation with one flip
Last Updated :
31 Oct, 2023
Give an integer n. We can flip exactly one bit. Write code to find the length of the longest sequence of 1 s you could create.
Examples:
Input : 1775
Output : 8
Binary representation of 1775 is 11011101111.
After flipping the highlighted bit, we get
consecutive 8 bits. 11011111111.
Input : 12
Output : 3
Input : 15
Output : 5
Input : 71
Output: 4
Binary representation of 71 is 1000111.
After flipping the highlighted bit, we get
consecutive 4 bits. 1001111.
A simple solution is to store the binary representation of a given number in a binary array. Once we have elements in a binary array, we can apply the methods discussed here.
An efficient solution is to walk through the bits in the binary representation of the given number. We keep track of the current 1's sequence length and the previous 1's sequence length. When we see a zero, update the previous Length:
- If the next bit is a 1, the previous Length should be set to the current Length.
- If the next bit is a 0, then we can’t merge these sequences together. So, set the previous Length to 0.
We update max length by comparing the following two:
- The current value of max-length
- Current-Length + Previous-Length .
- Result = return max-length+1 (// add 1 for flip bit count )
Below is the implementation of the above idea :
C++
// C++ program to find maximum consecutive
// 1's in binary representation of a number
// after flipping one bit.
#include<bits/stdc++.h>
using namespace std;
int flipBit(unsigned a)
{
/* If all bits are l, binary representation
of 'a' has all 1s */
if (~a == 0)
return 8*sizeof(int);
int currLen = 0, prevLen = 0, maxLen = 0;
while (a!= 0)
{
// If Current bit is a 1 then increment currLen++
if ((a & 1) == 1)
currLen++;
// If Current bit is a 0 then check next bit of a
else if ((a & 1) == 0)
{
/* Update prevLen to 0 (if next bit is 0)
or currLen (if next bit is 1). */
prevLen = (a & 2) == 0? 0 : currLen;
// If two consecutively bits are 0
// then currLen also will be 0.
currLen = 0;
}
// Update maxLen if required
maxLen = max(prevLen + currLen, maxLen);
// Remove last bit (Right shift)
a >>= 1;
}
// We can always have a sequence of
// at least one 1, this is flipped bit
return maxLen+1;
}
// Driver code
int main()
{
// input 1
cout << flipBit(13);
cout << endl;
// input 2
cout << flipBit(1775);
cout << endl;
// input 3
cout << flipBit(15);
return 0;
}
Java
// Java program to find maximum consecutive
// 1's in binary representation of a number
// after flipping one bit.
class GFG
{
static int flipBit(int a)
{
/* If all bits are l, binary representation
of 'a' has all 1s */
if (~a == 0)
{
return 8 * sizeof();
}
int currLen = 0, prevLen = 0, maxLen = 0;
while (a != 0)
{
// If Current bit is a 1
// then increment currLen++
if ((a & 1) == 1)
{
currLen++;
}
// If Current bit is a 0 then
// check next bit of a
else if ((a & 1) == 0)
{
/* Update prevLen to 0 (if next bit is 0)
or currLen (if next bit is 1). */
prevLen = (a & 2) == 0 ? 0 : currLen;
// If two consecutively bits are 0
// then currLen also will be 0.
currLen = 0;
}
// Update maxLen if required
maxLen = Math.max(prevLen + currLen, maxLen);
// Remove last bit (Right shift)
a >>= 1;
}
// We can always have a sequence of
// at least one 1, this is flipped bit
return maxLen + 1;
}
static byte sizeof()
{
byte sizeOfInteger = 8;
return sizeOfInteger;
}
// Driver code
public static void main(String[] args)
{
// input 1
System.out.println(flipBit(13));
// input 2
System.out.println(flipBit(1775));
// input 3
System.out.println(flipBit(15));
}
}
// This code is contributed by PrinciRaj1992
Python3
# Python3 program to find maximum
# consecutive 1's in binary
# representation of a number
# after flipping one bit.
def flipBit(a):
# If all bits are l,
# binary representation
# of 'a' has all 1s
if (~a == 0):
return 8 * sizeof();
currLen = 0;
prevLen = 0;
maxLen = 0;
while (a > 0):
# If Current bit is a 1
# then increment currLen++
if ((a & 1) == 1):
currLen += 1;
# If Current bit is a 0
# then check next bit of a
elif ((a & 1) == 0):
# Update prevLen to 0
# (if next bit is 0)
# or currLen (if next
# bit is 1). */
prevLen = 0 if((a & 2) == 0) else currLen;
# If two consecutively bits
# are 0 then currLen also
# will be 0.
currLen = 0;
# Update maxLen if required
maxLen = max(prevLen + currLen, maxLen);
# Remove last bit (Right shift)
a >>= 1;
# We can always have a sequence
# of at least one 1, this is
# flipped bit
return maxLen + 1;
# Driver code
# input 1
print(flipBit(13));
# input 2
print(flipBit(1775));
# input 3
print(flipBit(15));
# This code is contributed by mits
C#
// C# program to find maximum consecutive
// 1's in binary representation of a number
// after flipping one bit.
using System;
class GFG
{
static int flipBit(int a)
{
/* If all bits are l, binary representation
of 'a' has all 1s */
if (~a == 0)
{
return 8 * sizeof(int);
}
int currLen = 0, prevLen = 0, maxLen = 0;
while (a != 0)
{
// If Current bit is a 1
// then increment currLen++
if ((a & 1) == 1)
{
currLen++;
}
// If Current bit is a 0 then
// check next bit of a
else if ((a & 1) == 0)
{
/* Update prevLen to 0 (if next bit is 0)
or currLen (if next bit is 1). */
prevLen = (a & 2) == 0 ? 0 : currLen;
// If two consecutively bits are 0
// then currLen also will be 0.
currLen = 0;
}
// Update maxLen if required
maxLen = Math.Max(prevLen + currLen, maxLen);
// Remove last bit (Right shift)
a >>= 1;
}
// We can always have a sequence of
// at least one 1, this is flipped bit
return maxLen + 1;
}
// Driver code
public static void Main(String[] args)
{
// input 1
Console.WriteLine(flipBit(13));
// input 2
Console.WriteLine(flipBit(1775));
// input 3
Console.WriteLine(flipBit(15));
}
}
// This code contributed by Rajput-Ji
JavaScript
<script>
// Javascript program to
// find maximum consecutive
// 1's in binary representation
// of a number
// after flipping one bit.
function flipBit(a)
{
/* If all bits are l,
binary representation
of 'a' has all 1s */
if (~a == 0)
{
return 8 * sizeof(int);
}
let currLen = 0, prevLen = 0, maxLen = 0;
while (a != 0)
{
// If Current bit is a 1
// then increment currLen++
if ((a & 1) == 1)
{
currLen++;
}
// If Current bit is a 0 then
// check next bit of a
else if ((a & 1) == 0)
{
/* Update prevLen to 0
(if next bit is 0)
or currLen (if next bit is 1). */
prevLen = (a & 2) == 0 ? 0 : currLen;
// If two consecutively bits are 0
// then currLen also will be 0.
currLen = 0;
}
// Update maxLen if required
maxLen = Math.max(prevLen + currLen, maxLen);
// Remove last bit (Right shift)
a >>= 1;
}
// We can always have a sequence of
// at least one 1, this is flipped bit
return maxLen + 1;
}
// input 1
document.write(flipBit(13) + "</br>");
// input 2
document.write(flipBit(1775) + "</br>");
// input 3
document.write(flipBit(15));
</script>
PHP
<?php
// PHP program to find maximum consecutive
// 1's in binary representation of a number
// after flipping one bit.
function flipBit($a)
{
/* If all bits are l,
binary representation
of 'a' has all 1s */
if (~$a == 0)
return 8 * sizeof();
$currLen = 0;
$prevLen = 0;
$maxLen = 0;
while ($a!= 0)
{
// If Current bit is a 1
// then increment currLen++
if (($a & 1) == 1)
$currLen++;
// If Current bit is a 0
// then check next bit of a
else if (($a & 1) == 0)
{
/* Update prevLen to 0
(if next bit is 0)
or currLen (if next
bit is 1). */
$prevLen = ($a & 2) == 0? 0 : $currLen;
// If two consecutively bits are 0
// then currLen also will be 0.
$currLen = 0;
}
// Update maxLen if required
$maxLen = max($prevLen + $currLen, $maxLen);
// Remove last bit (Right shift)
$a >>= 1;
}
// We can always have a sequence of
// at least one 1, this is flipped bit
return $maxLen+1;
}
// Driver code
// input 1
echo flipBit(13);
echo "\n";
// input 2
echo flipBit(1775);
echo "\n";
// input 3
echo flipBit(15);
// This code is contributed by aj_36
?>
Time Complexity: O(log2n)
Auxiliary Space: O(1)
Approach 2: Sliding Window
In this approach, we can use a sliding window to count the length of the longest consecutive 1's. We can use two pointers to define a window and keep track of the number of flips we have made. When we encounter a 0, we can flip it and move the right pointer to the right. If the number of flips we have made is greater than 1, we can move the left pointer to the right until we have made only one flip. We can then update the maximum length obtained so far.
Here's the code:
C++
// C++ program to find maximum consecutive
// 1's in binary representation of a number
// after flipping one bit.
#include<bits/stdc++.h>
using namespace std;
int findMaxConsecutiveOnes(int num) {
int left = 0, right = 0, flips = 0, max_len = 0;
string binary = bitset<32>(num).to_string(); // convert integer to binary string
while (right < binary.size()) {
if (binary[right] == '0') {
flips++;
}
while (flips > 1) {
if (binary[left] == '0') {
flips--;
}
left++;
}
max_len = max(max_len, right - left + 1);
right++;
}
return max_len;
}
// Driver code
int main()
{
// input 1
cout << findMaxConsecutiveOnes(13);
cout << endl;
// input 2
cout << findMaxConsecutiveOnes(1775);
cout << endl;
// input 3
cout << findMaxConsecutiveOnes(15);
return 0;
}
Java
public class Main {
public static int findMaxConsecutiveOnes(int num) {
int left = 0, right = 0, flips = 0, max_len = 0;
String binary = String.format("%32s", Integer.toBinaryString(num)).replace(' ', '0');
while (right < binary.length()) {
if (binary.charAt(right) == '0') {
flips++;
}
while (flips > 1) {
if (binary.charAt(left) == '0') {
flips--;
}
left++;
}
max_len = Math.max(max_len, right - left + 1);
right++;
}
return max_len;
}
// Driver code
public static void main(String[] args) {
// input 1
System.out.println(findMaxConsecutiveOnes(13));
// input 2
System.out.println(findMaxConsecutiveOnes(1775));
// input 3
System.out.println(findMaxConsecutiveOnes(15));
}
}
Python3
# Python program to find maximum consecutive
# 1's in binary representation of a number
# after flipping one bit.
def findMaxConsecutiveOnes(num):
left, right, flips, max_len = 0, 0, 0, 0
binary = format(num, 'b').zfill(32) # convert integer to binary string
while right < len(binary):
if binary[right] == '0':
flips += 1
while flips > 1:
if binary[left] == '0':
flips -= 1
left += 1
max_len = max(max_len, right - left + 1)
right += 1
return max_len
# Driver code
if __name__ == "__main__":
# input 1
print(findMaxConsecutiveOnes(13))
# input 2
print(findMaxConsecutiveOnes(1775))
# input 3
print(findMaxConsecutiveOnes(15))
# This code is contributed by Susobhan Akhuli
C#
using System;
class GFG
{
// This function finds the length of the longest substring of ones
static int FindMaxConsecutiveOnes(int num)
{
int left = 0, right = 0, flips = 0, max_len = 0;
string binary = Convert.ToString(num, 2).PadLeft(32, '0'); // convert integer to binary string
// Iterating over the binary string
while (right < binary.Length)
{
if (binary[right] == '0')
flips++;
// Updating left index of the sliding window
while (flips > 1)
{
if (binary[left] == '0')
flips--;
left++;
}
// Updating maximum length
max_len = Math.Max(max_len, right - left + 1);
right++;
}
return max_len;
}
// Driver code
static void Main()
{
// input 1
Console.WriteLine(FindMaxConsecutiveOnes(13));
// input 2
Console.WriteLine(FindMaxConsecutiveOnes(1775));
// input 3
Console.WriteLine(FindMaxConsecutiveOnes(15));
}
}
// by phasing17
JavaScript
function findMaxConsecutiveOnes(num) {
let left = 0;
let right = 0;
let flips = 0;
let max_len = 0;
// Convert the integer to a binary string with a length of 32 bits
let binary = num.toString(2).padStart(32, '0');
// Iterate over the binary string
while (right < binary.length) {
if (binary[right] === '0') {
flips++;
}
// Update the left index of the sliding window
while (flips > 1) {
if (binary[left] === '0') {
flips--;
}
left++;
}
// Update the maximum length
max_len = Math.max(max_len, right - left + 1);
right++;
}
return max_len;
}
// Driver code
// Input 1
console.log("Max Consecutive 1's after flipping one bit in binary of 13:", findMaxConsecutiveOnes(13));
// Input 2
console.log("Max Consecutive 1's after flipping one bit in binary of 1775:", findMaxConsecutiveOnes(1775));
// Input 3
console.log("Max Consecutive 1's after flipping one bit in binary of 15:", findMaxConsecutiveOnes(15));
Time Complexity: O(n), where n is the number of bits in the binary representation of the given number.
Space Complexity: O(1)
This article is contributed by Mr. Somesh Awasthi.
Similar Reads
Basics & Prerequisites
Data Structures
Getting Started with Array Data StructureArray is a collection of items of the same variable type that are stored at contiguous memory locations. It is one of the most popular and simple data structures used in programming. Basic terminologies of ArrayArray Index: In an array, elements are identified by their indexes. Array index starts fr
14 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem