Data Structures & AlgorithmsEasyTCS NQT Digital · Product Company SDE

Problem: Count binary strings of length n with no two adjacent 1s, tracking how many valid strings end in 0 and in 1.

Problem: Count binary strings of length n with no two adjacent 1s, tracking how many valid strings end in 0 and in 1.
def no11(n):
    end0, end1 = 1, 1
    for _ in range(n - 1):
        end0, end1 = end0 + end1, end0
    return end0 + end1
print(no11(1), no11(3), no11(6))
What is printed?
  1. A. 2 5 21
  2. B. 2 4 21
  3. C. 1 5 21
  4. D. 2 5 13

Correct answer: A. 2 5 21

A string ending in 0 can extend any valid string; one ending in 1 must extend a string ending in 0. The totals follow Fibonacci: n = 1 → 2 (0, 1), n = 3 → 5 (000, 001, 010, 100, 101), n = 6 → 21. O(n) time, O(1) space.

More Coding Interview Problems questions

Exams that ask this topic