Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #600: Non-negative Integers without Consecutive Ones

In this guide, we solve Leetcode #600 Non-negative Integers without Consecutive Ones in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

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.

Quick Facts

  • Difficulty: Hard
  • Premium: No
  • Tags: Dynamic Programming

Intuition

The problem breaks into overlapping subproblems, so caching results prevents exponential repetition.

A carefully chosen DP state captures exactly what we need to build the final answer.

Approach

Define the DP state and recurrence, then compute states in the correct order.

Optionally compress space once the recurrence is clear.

Steps:

  • Choose a DP state definition.
  • Write the recurrence and base cases.
  • Compute states in the correct order.

Example

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.

Python Solution

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

The time complexity is O(log⁡n)O(\log n)O(logn), and the space complexity is O(log⁡n)O(\log n)O(logn). The space complexity is O(log⁡n)O(\log n)O(logn).

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy