Taro Logo

Non-negative Integers without Consecutive Ones

Hard
Asked by:
Pocket Gems
0 views
Topics:
Dynamic ProgrammingBit Manipulation

Given a positive integer n, return the number of the integers in the range [0, n] whose binary representations do not contain consecutive ones.

Example 1:

Input: n = 5
Output: 5
Explanation:
Here are the non-negative integers <= 5 with their corresponding binary representations:
0 : 0
1 : 1
2 : 10
3 : 11
4 : 100
5 : 101
Among them, only integer 3 disobeys the rule (two consecutive ones) and the other 5 satisfy the rule. 

Example 2:

Input: n = 1
Output: 2

Example 3:

Input: n = 2
Output: 3

Constraints:

  • 1 <= n <= 109

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the upper bound for the input integer $n$ (e.g., does it fit within a standard 32-bit signed integer)?
  2. Are we strictly considering non-negative integers from $0$ up to $n$ inclusive?
  3. Does the definition of "consecutive ones" apply strictly to adjacent bits in the binary representation of the integers?
  4. Should 0 and 1 be counted as valid numbers since their binary representations do not contain consecutive ones?
  5. Is the expected return type a standard integer or should I account for larger return values using a 64-bit integer?

Brute Force Solution

Approach

To find all numbers up to a given limit that do not have consecutive ones in their binary form, the brute force approach checks every single number starting from zero up to that limit. For each number, it inspects its binary representation to see if any two ones appear right next to each other.

Here's how the algorithm would work step-by-step:

  1. Begin with the number zero and consider it as the first candidate.
  2. Translate the current number into its binary representation made of zeros and ones.
  3. Examine the binary version closely to see if any two ones are standing side by side.
  4. If there are indeed two ones sitting next to each other, discard this number from our count.
  5. If there are no consecutive ones, keep this number as a valid success.
  6. Move on to the next consecutive whole number and repeat the entire checking process.
  7. Continue this check for every single number all the way up to the given upper limit.
  8. Count up all the numbers that successfully passed the test without any consecutive ones to get the final answer.

Code Implementation

def find_integers(upper_limit: int) -> int:
    valid_number_count = 0

    # Iterate through every integer from zero up to the upper limit to evaluate them individually
    for current_number in range(upper_limit + 1):
        binary_representation = bin(current_number)[2:]
        has_consecutive_ones = False

        # Scan adjacent character pairs to detect any forbidden consecutive ones in the binary string
        for character_index in range(len(binary_representation) - 1):
            if binary_representation[character_index] == '1' and binary_representation[character_index + 1] == '1':
                has_consecutive_ones = True
                break

        # Exclude numbers with consecutive ones to ensure only strictly valid integers increase our tally
        if not has_consecutive_ones:
            valid_number_count += 1

    return valid_number_count

Big(O) Analysis

Time Complexity
O(n log n) – To solve this, we iterate through every single integer starting from zero up to the given upper limit n. For each of these n numbers, we must examine its binary representation to check for consecutive ones, which takes proportional time to the number of bits, roughly log base 2 of the number. Therefore, the total operations scale as n multiplied by log n. This product gives us a final simplified runtime of O(n log n).
Space Complexity
O(log N) – The space complexity is driven by the translation of each candidate number into its binary representation and the tracking variables used during the iteration up to the upper limit N. Specifically, storing the binary string or inspecting its bits requires auxiliary space proportional to the number of bits in N, which is logarithmic relative to N. Furthermore, only a few primitive integer variables are used to maintain the loop state and counts without requiring dynamic data structures or recursion. Thus, the extra memory usage scales logarithmically with the input size N, simplifying to Big O of log N.

Optimal Solution

Approach

Instead of checking every single number one by one, the optimal approach uses the patterns of binary numbers to count valid options efficiently by breaking the limit down piece by piece. It relies on the relationship between position lengths and known patterns of valid sequences to skip massive blocks of numbers all at once.

Here's how the algorithm would work step-by-step:

  1. Translate the upper limit number into its binary representation so we can look at its structure from the biggest place value down to the smallest.
  2. Examine the binary sequence for any spots where two ones appear right next to each other, because any number containing this forbidden pattern must be avoided.
  3. Notice that for any fixed length of binary digits, the total count of valid numbers without adjacent ones follows a very famous predictable pattern where each step is the sum of the previous two steps.
  4. Scan the target number from left to right to find the most significant position where a one appears.
  5. Whenever you find a one at a certain position, you can safely add up all the valid combinations that can fit in all the smaller positions to the right, because we know every combination starting with a zero there will be valid.
  6. If you encounter a spot where two ones appear consecutively in the target number itself, stop right there because any number sharing that prefix would also violate the rule, meaning we cannot explore further down that path.
  7. Continue this process for the remaining parts of the number, adding up the valid groups until you reach the end, giving you the total count instantly without wasting time on brute force counting.

Code Implementation

class Solution:
    def find_integers(self, limit_number: int) -> int:
        binary_representation = bin(limit_number)[2:]
        length_of_binary = len(binary_representation)

        fibonacci_sequence = [0] * (length_of_binary + 2)
        fibonacci_sequence[0] = 1
        fibonacci_sequence[1] = 2

        for index in range(2, length_of_binary + 2):
            fibonacci_sequence[index] = fibonacci_sequence[index - 1] + fibonacci_sequence[index - 2]

        total_valid_count = 0
        previous_bit_was_one = False

        # Precompute valid counts for lengths to quickly sum valid combinations.
        for index, character in enumerate(binary_representation):
            power_of_two = length_of_binary - 1 - index
            if character == '1':
                total_valid_count += fibonacci_sequence[power_of_two]
                if previous_bit_was_one:
                    return total_valid_count - fibonacci_sequence[power_of_two]
                previous_bit_was_one = True
            else:
                previous_bit_was_one = False

        # Add one more to include the upper limit number itself if it is valid.
        return total_valid_count + 1

Big(O) Analysis

Time Complexity
O(log n) – The cost is driven by the number of bits in the upper limit n, since the algorithm processes the binary representation of n from left to right. Translating the integer to binary and scanning its digits takes a number of steps proportional to the bit length of n, which is base-2 logarithmic. Precomputing the valid sequence counts takes a constant number of steps based on the maximum bit length of 32. This yields approximately 32 operations in the worst case, which simplifies to O(log n).
Space Complexity
O(log N) – To analyze the space complexity, let N be the input integer whose binary representation we examine from left to right. The algorithm requires auxiliary storage for the binary digits of N and two precomputed arrays of Fibonacci numbers. Since the number of bits in a binary representation grows logarithmically with the value of N, the length of these structures is proportional to log base 2 of N. Therefore, the extra memory required scales with the bit-length of the input, resulting in an efficient logarithmic auxiliary space complexity.

Edge Cases

Input n equals zero
How to Handle:
The algorithm should correctly return 1 because zero itself has no consecutive ones and is less than or equal to zero.
Input n equals one
How to Handle:
The algorithm should return 2 since both zero and one are valid non-negative integers without consecutive ones.
Input n is a power of two minus one, such as 3 or 7, where the binary representation is all ones
How to Handle:
The digit DP or bit manipulation approach will correctly terminate at the highest threshold without overcounting.
Maximum possible integer limits up to 10 to the 9th power or 32-bit integer limits
How to Handle:
Using iterative digit DP or precomputed Fibonacci numbers prevents recursion depth limits and avoids integer overflow during intermediate Fibonacci sums.
Inputs with alternating binary bits like 1010 in binary which equals 10
How to Handle:
The state transition in the bit-counting logic will properly validate each bit position without prematurely stopping.
Inputs where n has pre-existing consecutive ones in its binary representation
How to Handle:
The algorithm must correctly detect the violation, stop branching down invalid paths, and count all valid numbers strictly below that prefix.