Data Structures & AlgorithmsModerateInfosys SP/DSE · Product Company SDE

Problem: Climbing-stairs memoisation in Python:

Problem: Climbing-stairs memoisation in Python:
def ways(n, memo={}):
    if n <= 1: return 1
    if n in memo: return memo[n]
    memo[n] = ways(n - 1) + ways(n - 2)
    return memo[n]
What is the subtle issue with this code?
  1. A. It recomputes everything, giving O(2ⁿ)
  2. B. It raises KeyError for n = 2
  3. C. memo is reset on every call, so it is not memoised
  4. D. The default dict is created once and shared across all calls – fine here, but it leaks state between unrelated uses and tests

Correct answer: D. The default dict is created once and shared across all calls – fine here, but it leaks state between unrelated uses and tests

Default argument values are evaluated once when def runs, so memo persists across calls. For this pure function it even speeds things up, but with a different problem or inputs (e.g. a changing coin set) cached answers would be wrong. Recursion still runs O(n) deep.

More Coding Interview Problems questions

Exams that ask this topic