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?- A. It recomputes everything, giving O(2ⁿ)
- B. It raises KeyError for n = 2
- C. memo is reset on every call, so it is not memoised
- 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
- Problem: Reverse a singly linked list (C++): cpp Node prev = nullptr; while (head) { head->next = prev; // line 3 prev = head; head =…
- Problem: A sliding-window solution for 'longest substring with at most k distinct characters' keeps a frequency map and shrinks while…
- Problem: Merge sort's merge step in Java uses if (a[i] < b[j]) take a[i]; else take b[j];. What property is lost compared with <=?
- Problem: The 'two-sum on a sorted array' code below has a subtle edge-case behaviour. What does it print? python def twosumsorted(a, t)…
- Problem: A ride app must repeatedly add drivers with ratings and remove the highest-rated driver, n = 10⁵ operations. Which data structure…
- Problem: A leaderboard needs: insert a score, delete a score, and 'how many scores are below x?' – all online, 10⁵ operations, scores up…