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?- A. 2 5 21
- B. 2 4 21
- C. 1 5 21
- 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
- Problem: Find the minimum sum of a falling path through a square grid: start anywhere in the top row and move to one of the (up to) three…
- Problem: Minimum path sum from the top of a number triangle to the bottom (step to the same index or index + 1 in the next row), computed…
- Problem: Pairs (a, b) with a < b can be chained when the next pair's a is strictly greater than the previous b. Find the longest chain…
- Problem: Paint a row of houses with 3 colours so that neighbours differ; costs[i] = cost of each colour for house i. Minimise the total…
- Problem: Split an integer n ≥ 2 into at least two positive parts to maximise the product of the parts. python def intbreak(n): dp = [0, 1]…
- Problem: A cable of length n is cut into pieces; prices[k − 1] is the price of a piece of length k. Maximise revenue (unbounded knapsack)…