Non-Negative Integers Without Consecutive Ones Problem
Description
LeetCode Problem 600.
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 <= 10^9
Solution
Approach: Fibonacci Counts over the Bits of n
Checking every number up to n = 109 is far too slow. Instead, count valid numbers in whole blocks.
Counting strings of a fixed length. Let fib[i] be the number of binary strings of length i with no two adjacent 1s. A valid string either starts with 0 (followed by any valid string of length i - 1) or starts with 10 (followed by any valid string of length i - 2). So fib[i] = fib[i - 1] + fib[i - 2], with fib[0] = 1 and fib[1] = 2.
Walking the bits of n from the top. Every number below n agrees with n on some prefix and then has a 0 where n has a 1. So for each set bit at position bit:
- Count the numbers that copy
nabove this position, put a0here, and use any valid string for thebitlower bits: that isfib[bit]numbers. - Then keep the
1and continue. If the previous bit was also1, every remaining number (includingn) has the prefix11, so stop and return the count.
If the loop finishes, n itself has no adjacent 1s, so add 1.
For n = 5 (101): bit 2 adds fib[2] = 3 (000, 001, 010), bit 0 adds fib[0] = 1 (100), and n adds 1, giving 5.
The detail that is easy to miss: the prefix copied from n must itself be valid, which is why we stop at the first 11 in n.
Complexity: O(B) time and O(B) space for the fib table, where B = 31 is the number of bits checked (n ≤ 109 < 230).
class Solution:
def findIntegers(self, n: int) -> int:
# fib[i] = how many binary strings of length i have no two adjacent 1s
fib = [1, 2]
for i in range(2, 31):
fib.append(fib[i - 1] + fib[i - 2])
count = 0
prev_bit_set = False
for bit in range(30, -1, -1): # n <= 10^9 < 2^30
if n & (1 << bit):
# Put 0 here instead: the lower `bit` bits can be any valid string.
count += fib[bit]
if prev_bit_set:
return count # n's prefix has "11", so no larger number counts
prev_bit_set = True
else:
prev_bit_set = False
return count + 1 # n itself is valid
Now write it from memory
Close the write-up and solve it yourself against the tests.