Solving Leetcode Interviews in Seconds with AI: Non-negative Integers without Consecutive Ones
Introduction
In this blog post, we will explore how to solve the LeetCode problem "600" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.
Problem Statement
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
Explanation
Here's the solution:
Fibonacci Connection: The number of integers with no consecutive ones and having k bits is closely related to the Fibonacci sequence. Let
fib[i]be the number of such integers with i bits. Thenfib[i] = fib[i-1] + fib[i-2], with base casesfib[0] = 1andfib[1] = 2.Digit-by-Digit Analysis: Convert the input
nto its binary representation. Iterate through the bits from the most significant bit to the least significant bit. For each bit, consider two cases: if the current bit is 1, addfib[remaining_bits]to the result. If the previous bit was also 1, then stop, because all subsequent numbers will violate the consecutive ones rule.Dynamic Programming (Fibonacci Calculation): Precompute the Fibonacci numbers needed up to the maximum possible number of bits (which is 32 because n <= 109).
Complexity: O(log n) time, O(log n) space.
Code
def find_integers(n: int) -> int:
"""
Given a positive integer n, return the number of the integers in the range [0, n]
whose binary representations do not contain consecutive ones.
"""
# Precompute Fibonacci numbers up to 32 (maximum bits for n <= 10^9)
fib = [0] * 32
fib[0] = 1
fib[1] = 2
for i in range(2, 32):
fib[i] = fib[i - 1] + fib[i - 2]
# Convert n to binary representation
binary = bin(n)[2:]
length = len(binary)
count = 0
prev_bit = 0
for i in range(length):
if binary[i] == '1':
count += fib[length - i - 1]
if prev_bit == 1:
return count # Consecutive ones found, stop here
prev_bit = 1
else:
prev_bit = 0
return count + 1 # Add 1 to include n itself if no consecutive ones found