VOOZH about

URL: https://www.geeksforgeeks.org/dsa/count-of-non-consecutive-ones-in-binary-range/

⇱ Count of non-consecutive Ones in Binary range - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Count of non-consecutive Ones in Binary range

Last Updated : 23 Jul, 2025

Given two positive integers 'L' and 'R', the task is to return the number of the integers in the range [L, R] inclusive, whose binary representations do not contain consecutive ones where 0 ≤ l ≤ r ≤ 10^9

Examples:

Input: L = 0, R = 3
Output: 3
Explanation: The 3 numbers are 0(00), 1(01), 2(10) 3(11) is not included as its binary representation contains consecutive ones

Input: L = 5, R = 10
Output: 4
Explanation: The 4 numbers are 5(101), 8(1000), 9(1001), 10(1010)

Solving problem usingDigit Dynamic Programming:

If we say G(x) tells the number of such integers between 0 to x (inclusively) without consecutive 1's in their binary representation, then the number of such integers between L and R can be given by G(R) – G(L-1). This is when Digit DP (Dynamic Programming) comes into action. All such integer counting problems that satisfy the above property can be solved by the digit DP approach.

Intuition:

If we use the Digit DP approach to build all the binary String from the [ 0, R ] range and [0, L-1] range. then return Numbers in [0, R] range - Numbers in [0, L-1] range. So, we have only 2 digits to form the binary number i.e. 1 and 0.

Steps to solve the above approach:

  • The algorithm iterates through each digit position of the binary representation of 10^9 i.e. it's 32-bit long.
  • It keeps track of the previous digit, whether it's 0, 1, or an initial state
  • It considers a "tight" flag that determines the upper bound of the current digit based on the previous digits and the given range.
  • It recursively calculates the count of valid integers by considering all possible digits at each position, excluding combinations with consecutive 1s.
  • The algorithm sums up the counts from all recursive calls and memoizes the result for future use.
  • Finally, the algorithm returns the count of valid integers within the given range by subtracting the count of valid integers from the [L, R] range inclusively.

Below is the implementation of the above approach:


Output
3
4
2178302

Time Complexity: O(2*idx*prev*tight)
Auxiliary Space: O(idx * prev* tight)

Comment