Data Structures & AlgorithmsHardAmazon · Microsoft OA

Problem: Count the ways to climb n stairs taking 1, 3 or 5 steps at a time (order matters).

Problem: Count the ways to climb n stairs taking 1, 3 or 5 steps at a time (order matters).
def ways(n):
    dp = [1] + [0] * n
    for i in range(1, n + 1):
        dp[i] = sum(dp[i - s] for s in (1, 3, 5) if s <= i)
    return dp[n]
print(ways(10))
What is printed?
  1. A. 47
  2. B. 30
  3. C. 55
  4. D. 39

Correct answer: A. 47

dp: 1, 1, 1, 2, 3, 5, 8, 12, 19, 30, 47 for n = 0..10, using dp[i] = dp[i−1] + dp[i−3] + dp[i−5]. Counting unordered combinations instead would be far fewer.

More Coding Interview Problems questions

Exams that ask this topic