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
Fibonacci Pattern in Binary ValidationLength 1: {0, 1} → Count = 2Length 2: {00, 01, 10} → Count = 3 (exclude 11)Length 3: {000, 001, 010, 100, 101} → Count = 5Fibonacci SequenceF(1) = 2F(2) = 3 = F(1) + F(0)F(3) = 5 = F(2) + F(1)F(n) = F(n-1) + F(n-2)Why Fibonacci?For valid string of length n:• If it ends with 0: previous n-1 chars can be any valid string• If it ends with 1: previous char must be 0, so we needvalid string of length n-2 + "01"Total: F(n) = F(n-1) + F(n-2)Digit DP for Upper Bound• Process binary digits of n from left to right• At each position, count valid continuations• Use Fibonacci values for remaining positions• Handle consecutive 1s constraintExample: n = 5 (binary: 101)Position 0 (bit=1): Add F(2)=3 for all "0XX" patternsPosition 2 (bit=1): Add F(0)=1 for "X01" patterns + 1 for n itself = 5 total
Understanding the Visualization
1
Pattern Recognition
Valid strings of length n = Valid strings ending in 0 + Valid strings ending in 1
2
Recurrence Relation
If string ends in 0, previous bit can be 0 or 1. If ends in 1, previous must be 0
3
Fibonacci Connection
This gives us F(n) = F(n-1) + F(n-2), the Fibonacci recurrence
Key Takeaway
🎯 Key Insight: The problem combines Fibonacci sequence properties with digit DP technique to efficiently count valid numbers without checking each one individually.
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