Non-negative Integers without Consecutive Ones - Problem

Given a positive integer n, you need to count how many integers in the range [0, n] have binary representations without consecutive ones.

In binary representation, consecutive ones mean two or more 1s appearing next to each other. For example:

  • 5 (101₂) ✅ Valid - no consecutive ones
  • 6 (110₂) ❌ Invalid - has consecutive ones
  • 3 (11₂) ❌ Invalid - has consecutive ones

Your task is to efficiently count all valid numbers from 0 to n inclusive that satisfy this constraint.

Challenge: Can you solve this without checking every single number individually?

Input & Output

example_1.py — Basic Case
$ Input: n = 5
Output: 5
💡 Note: The valid numbers are: 0 (0₂), 1 (1₂), 2 (10₂), 4 (100₂), 5 (101₂). Number 3 (11₂) and 6 (110₂) have consecutive ones, but 6 > 5 anyway.
example_2.py — Larger Number
$ Input: n = 8
Output: 6
💡 Note: Valid numbers: 0 (0₂), 1 (1₂), 2 (10₂), 4 (100₂), 5 (101₂), 8 (1000₂). Numbers 3, 6, 7 have consecutive 1s in binary.
example_3.py — Edge Case
$ Input: n = 1
Output: 2
💡 Note: Valid numbers are 0 (0₂) and 1 (1₂). Both have no consecutive ones since they're single bits.

Constraints

  • 1 ≤ n ≤ 109
  • n is a positive integer
  • Binary representation constraint: No consecutive 1s allowed

Visualization

Tap to expand
Non-negative Integers without Consecutive Ones INPUT n = 5 Numbers 0 to 5 in Binary: 0: 000 OK 1: 001 OK 2: 010 OK 3: 011 X 4: 100 OK 5: 101 OK Consecutive 1s Example: 3 = 011 (has "11") 6 = 110 (has "11") Range: [0, 5] ALGORITHM (DP) 1 Build Fibonacci-like DP f[i] = valid nums with i bits i: 1 2 3 4 5 f[i]: 2 3 5 8 13 2 Digit DP Traversal Process bits from MSB 5 = 1 0 1 Scan: pos 2 --> 1 --> 0 3 Count Valid Prefixes Add f[i] when bit=1 At bit 2: add f[2] = 3 At bit 0: add f[0] = 1 Plus n itself if valid 4 Sum All Counts 3 + 1 + 1 = 5 FINAL RESULT Valid Numbers (No Consecutive 1s): 0 000 1 001 2 010 4 100 5 101 Output: 5 5 valid integers found in range [0, 5] Excluded: 3 (011 has "11") Key Insight: Valid counts follow Fibonacci pattern! f[i] = f[i-1] + f[i-2]. Use digit DP to count numbers without consecutive 1s by processing bits from MSB. When current bit is 1, add count of all valid numbers with 0 at that position. Time complexity: O(log n) instead of O(n)! TutorialsPoint - Non-negative Integers without Consecutive Ones | DP Approach
Asked in
Google 25 Amazon 18 Microsoft 15 Meta 12
28.4K Views
Medium Frequency
~35 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen