Data Structures & AlgorithmsEasyTCS NQT Digital · Product Company SDE
Problem: A staircase has n steps; you climb 1 or 2 steps at a time. Count the distinct ways to reach the top.
Problem: A staircase has n steps; you climb 1 or 2 steps at a time. Count the distinct ways to reach the top.
long long ways(int n) {
long long a = 1, b = 1; // ways(0), ways(1)
for (int i = 2; i <= n; i++) {
long long c = a + b;
a = b; b = c;
}
return b;
}
// ways(10)What does ways(10) return?- A. 55
- B. 89
- C. 144
- D. 100
Correct answer: B. 89
ways(n) = ways(n − 1) + ways(n − 2) with ways(0) = ways(1) = 1, the Fibonacci numbers shifted by one: 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89. Answering 55 confuses it with F(10). O(n) time, O(1) space; the naive recursion is O(φⁿ).
More Coding Interview Problems questions
- Problem: A thief robs houses in a row but cannot rob two adjacent houses. Find the maximum loot. python def rob(a): take = skip = 0 for x…
- Problem: Same robbery, but the houses form a circle (first and last are adjacent). python def line(a): take = skip = 0 for x in a: take…
- Problem: Find the fewest coins that make an amount (−1 if impossible). python def coins(cs, amt): INF = float('inf'); dp = [0] + [INF] amt…
- Problem: Count the number of ways to make an amount from unlimited coins, where order does not matter. python def ways(cs, amt): dp = [1]…
- Problem: 0/1 knapsack with a 1-D array. The candidate below loops capacity upwards. python def wrong(w, v, W): dp = [0] (W + 1) for i in…
- Problem: 0/1 knapsack – maximise value within capacity W. cpp int knap(vector<int> w, vector<int> v, int W) { vector<int> dp(W + 1, 0)…