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?- A. 47
- B. 30
- C. 55
- 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
- Problem: Fractional knapsack — take items (or fractions) by value/weight ratio to maximise value within capacity. python def frac(items…
- Problem: One pass of Lomuto partition (pivot = last element) as used in quicksort. python def lomuto(a): p = a[-1]; i = -1 for j in…
- Problem: Count the swaps made by bubble sort and by selection sort on the same array. python def bubble(a): a = a[:]; s = 0 for i in…
- Problem: Bottom-up heapify (max-heap) of an array; print the resulting array. python def heapify(a): n = len(a) def down(i): while True…
- Problem: Insert keys into a hash table of size 7 with open addressing and LINEAR probing, h(k) = k mod 7. python T = [None] 7 for k in…
- Problem: Double hashing with h1(k) = k mod 11 and h2(k) = 7 − (k mod 7); probe i is (h1 + i·h2) mod 11. Print the slots probed for key 58…