#600

Non-negative Integers without Consecutive Ones

Hard
Dynamic ProgrammingDynamic ProgrammingBit Manipulation
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(log n)
Space
O(1)
O(1)
💡

Intuition

Time O(log n)Space O(1)

The optimal solution uses dynamic programming to count valid numbers based on their binary representation. We can leverage the Fibonacci sequence to determine how many valid numbers exist up to a certain bit length without consecutive ones.

⚙️

Algorithm

5 steps
  1. 1Step 1: Create an array dp where dp[i] represents the count of valid numbers with i bits.
  2. 2Step 2: Initialize dp[0] = 1 (the empty number) and dp[1] = 2 (0 and 1).
  3. 3Step 3: Fill dp[i] using the relation dp[i] = dp[i-1] + dp[i-2] for i from 2 to the number of bits in n.
  4. 4Step 4: Count valid numbers less than or equal to n by checking each bit of n from the most significant to the least significant, using dp to count valid configurations.
  5. 5Step 5: Return the total count.
solution.py16 lines
1# Full working Python code
2def findIntegers(n):
3    dp = [0] * 32
4    dp[0], dp[1] = 1, 2
5    for i in range(2, 32):
6        dp[i] = dp[i - 1] + dp[i - 2]
7    count, prev_bit = 0, 0
8    for i in range(31, -1, -1):
9        if (n & (1 << i)):
10            count += dp[i]
11            if prev_bit:
12                return count
13            prev_bit = 1
14        else:
15            prev_bit = 0
16    return count + 1

Complexity note: The time complexity is O(log n) because we only iterate through the bits of n, which is at most 32 for the given constraints.

  • 1The Fibonacci sequence helps in counting valid configurations without consecutive ones.
  • 2Understanding binary representation is crucial for efficiently solving this problem.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.