600. Non-negative Integers without Consecutive Ones
HardSolutions in Python, Java, C++, TypeScript
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
Method: Digit DP on Binary Representation
This problem asks for the count of integers in [0, n] whose binary representation does not contain consecutive ones. A brute-force approach of checking each number up to n would be too slow given the constraint n <= 10^9. This suggests a more efficient method, and the nature of the problem (counting numbers based on digit properties) points towards Digit DP.
Solution
Non-negative Integers without Consecutive Ones in Python
class Solution:
def findIntegers(self, n: int) -> int:
# We count valid numbers < n+1. This is a common Digit DP trick.
# It avoids having to handle the number n itself as a special case.
s = bin(n + 1)[2:]
length = len(s)
# f[i] = number of valid binary strings of length i
# This is a Fibonacci sequence: f[i] = f[i-1] + f[i-2]
f = [0] * (length + 1)
f[0] = 1 # empty string
f[1] = 2 # "0", "1"
for i in range(2, length + 1):
f[i] = f[i - 1] + f[i - 2]
ans = 0
prev_bit_is_one = False
# Iterate through the bits of s from MSB to LSB
for i in range(length):
# If the current bit of s is '1'
if s[i] == '1':
# We can place a '0' here. The remaining length - 1 - i bits
# can be any valid combination. The number of such combinations
# is f[length - 1 - i].
ans += f[length - 1 - i]
# If the previous bit was also '1', we have "11".
# Any number with this prefix is invalid. All smaller valid numbers
# have been counted, so we can stop.
if prev_bit_is_one:
return ans
prev_bit_is_one = True
# If the current bit of s is '0'
else:
# We must place '0' to stay on a path <= n+1.
prev_bit_is_one = False
return ans
Non-negative Integers without Consecutive Ones in Java
class Solution {
public int findIntegers(int n) {
// Convert n+1 to its binary representation string.
// We use n+1 to count numbers in [0, n], which is equivalent to counting numbers < n+1.
// This simplifies the logic by avoiding a final check on n itself.
String s = Integer.toBinaryString(n + 1);
int len = s.length();
// f[i] will store the number of i-bit binary strings without consecutive ones.
// This follows a Fibonacci-like sequence: f[i] = f[i-1] + f[i-2].
int[] f = new int[len + 1];
f[0] = 1; // Base case: empty string
f[1] = 2; // "0", "1"
for (int i = 2; i <= len; i++) {
f[i] = f[i - 1] + f[i - 2];
}
int ans = 0;
boolean prevIsOne = false;
// Iterate through the bits of s from MSB to LSB.
for (int i = 0; i < len; i++) {
if (s.charAt(i) == '1') {
// If the current bit in s is '1', we can form smaller valid numbers
// by placing a '0' at this position. The remaining (len - 1 - i) bits
// can be any valid binary string of that length.
// The number of such strings is f[len - 1 - i].
ans += f[len - 1 - i];
// If the previous bit was also '1', we have found "11".
// Any number with this prefix is invalid. Since we have already counted
// all valid numbers smaller than the current prefix, we can stop.
if (prevIsOne) {
return ans;
}
prevIsOne = true;
} else { // s.charAt(i) == '0'
// If the current bit is '0', we must also place a '0' to stay
// smaller than or equal to n+1. No other branches to count here.
prevIsOne = false;
}
}
return ans;
}
}
Non-negative Integers without Consecutive Ones in C++
class Solution {
public:
int findIntegers(int n) {
// Convert n+1 to its binary representation string.
// We use n+1 to count numbers in [0, n], which is equivalent to counting numbers < n+1.
// This simplifies the logic by avoiding a final check on n itself.
string s = "";
int temp = n + 1;
while (temp > 0) {
s += (temp % 2 == 0 ? '0' : '1');
temp /= 2;
}
reverse(s.begin(), s.end());
int len = s.length();
// f[i] will store the number of i-bit integers without consecutive ones.
// This follows a Fibonacci-like sequence.
vector<int> f(len + 1);
f[0] = 1; // Base case: empty string
f[1] = 2; // "0", "1"
for (int i = 2; i <= len; ++i) {
f[i] = f[i - 1] + f[i - 2];
}
int ans = 0;
bool prev_is_one = false;
// Iterate through the bits of s from MSB to LSB.
for (int i = 0; i < len; ++i) {
if (s[i] == '1') {
// If current bit in s is '1', we can form smaller numbers by placing '0' here.
// The remaining (len - 1 - i) bits can be any valid sequence.
// The number of valid sequences of length (len - 1 - i) is f[len - 1 - i].
ans += f[len - 1 - i];
// If the previous bit was also '1', we have found "11".
// Any number with this prefix is invalid. Since we have already counted
// all valid numbers smaller than the current prefix, we can stop.
if (prev_is_one) {
return ans;
}
prev_is_one = true;
} else { // s[i] == '0'
// If current bit is '0', we must place '0' to stay smaller than or equal to n+1.
// No other branches to count here.
prev_is_one = false;
}
}
return ans;
}
};
Non-negative Integers without Consecutive Ones in TypeScript
function findIntegers(n: number): number {
// We count valid numbers < n+1. This is a common Digit DP trick.
// It avoids having to handle the number n itself as a special case.
const s = (n + 1).toString(2);
const len = s.length;
// f[i] = number of valid binary strings of length i
// This is a Fibonacci sequence: f[i] = f[i-1] + f[i-2]
const f: number[] = new Array(len + 1).fill(0);
f[0] = 1; // empty string
f[1] = 2; // "0", "1"
for (let i = 2; i <= len; i++) {
f[i] = f[i - 1] + f[i - 2];
}
let ans = 0;
let prevIsOne = false;
// Iterate through the bits of s from MSB to LSB
for (let i = 0; i < len; i++) {
if (s[i] === '1') {
// If the current bit in s is '1', we can form smaller valid numbers
// by placing a '0' at this position. The remaining (len - 1 - i) bits
// can be any valid binary string of that length.
// The number of such strings is f[len - 1 - i].
ans += f[len - 1 - i];
// If the previous bit was also '1', we have found "11".
// Any number with this prefix is invalid. Since we have already counted
// all valid numbers smaller than the current prefix, we can stop.
if (prevIsOne) {
return ans;
}
prevIsOne = true;
} else { // s[i] === '0'
// If the current bit is '0', we must also place a '0' to stay
// smaller than or equal to n+1. No other branches to count here.
prevIsOne = false;
}
}
return ans;
};
More Hard LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.