HardNo. 0600

Non-negative Integers without Consecutive Ones — LeetCode 600 Python Solution

Topics
Dynamic Programming
Reading time
3 min

The problem

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

Input
n = 5
Output
5
Explanation
Here are the non-negative integers <= 5 with their corresponding binary representations:

Python solution

PythonSolution
class Solution:
    def findIntegers(self, n: int) -> int:
        @cache
        def dfs(i: int, pre: int, limit: bool) -> int:
            if i < 0:
                return 1
            up = (n >> i & 1) if limit else 1
            ans = 0
            for j in range(up + 1):
                if pre and j:
                    continue
                ans += dfs(i - 1, j, limit and j == up)
            return ans

        return dfs(n.bit_length() - 1, 0, True)

Complexity

Time
O(log n)
Space · auxiliary
O(log n)

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 600. Non-negative Integers without Consecutive Ones is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.

The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0010Regular Expression MatchingHard
0022Generate ParenthesesMedium
0032Longest Valid ParenthesesHard
0044Wildcard MatchingHard
0045Jump Game IIMedium
0053Maximum SubarrayMedium

Frequently asked questions

How hard is LeetCode 600. Non-negative Integers without Consecutive Ones?

LeetCode 600. Non-negative Integers without Consecutive Ones is rated Hard on LeetCode.

What is the time complexity of LeetCode 600. Non-negative Integers without Consecutive Ones?

The Python solution on this page runs in O(log n).

What is the space complexity of LeetCode 600. Non-negative Integers without Consecutive Ones?

The Python solution on this page uses O(log n) auxiliary space.

What topics does LeetCode 600. Non-negative Integers without Consecutive Ones cover?

LeetCode 600. Non-negative Integers without Consecutive Ones is tagged Dynamic Programming on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.