Data Structures & AlgorithmsModerateTCS NQT Digital · Product Company SDE

Problem: Count the number of ways to climb n stairs taking 1, 2 or 3 steps, modulo 10⁹ + 7.

Problem: Count the number of ways to climb n stairs taking 1, 2 or 3 steps, modulo 10⁹ + 7.
static long ways3(int n) {
    long MOD = 1_000_000_007L;
    long[] dp = new long[Math.max(n + 1, 3)];
    dp[0] = 1; dp[1] = 1; dp[2] = 2;
    for (int i = 3; i <= n; i++)
        dp[i] = (dp[i-1] + dp[i-2] + dp[i-3]) % MOD;
    return dp[n];
}
// ways3(5) + " " + ways3(10) + " " + ways3(0)
What does the commented expression evaluate to?
  1. A. 13 274 0
  2. B. 13 274 1
  3. C. 8 274 1
  4. D. 13 149 1

Correct answer: B. 13 274 1

Tribonacci: 1, 1, 2, 4, 7, 13, 24, 44, 81, 149, 274. The array is sized at least 3 so dp[2] exists even for n = 0, and dp[0] = 1 (one way: do nothing). O(n).

More Coding Interview Problems questions

Exams that ask this topic