VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-longest-sequence-1s-binary-representation-one-flip/

⇱ Find longest sequence of 1's in binary representation with one flip - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

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:  

  1. If the next bit is a 1, the previous Length should be set to the current Length.
  2. 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:  

  1. The current value of max-length
  2. Current-Length + Previous-Length .
  • Result = return max-length+1 (// add 1 for flip bit count )

Below is the implementation of the above idea : 


Output
4
8
5

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:


Output
4
8
5

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.

Comment
Article Tags: