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?
  1. A. 55
  2. B. 89
  3. C. 144
  4. 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

Exams that ask this topic