Data Structures & AlgorithmsVery hardProduct company OA
A memoised recursion f(n) = f(n//2) + f(n//3) + f(n//6) is evaluated for n = 10¹². How many distinct calls (cache misses) are made?
A memoised recursion f(n) = f(n//2) + f(n//3) + f(n//6) is evaluated for n = 10¹². How many distinct calls (cache misses) are made?
from functools import lru_cache
calls = 0
@lru_cache(None)
def f(n):
global calls; calls += 1
if n == 0: return 1
return f(n // 2) + f(n // 3) + f(n // 6)
print(f(10**12) > 0, calls)- A. True 40
- B. True 1000000
- C. True 438
- D. True 1365
Correct answer: C. True 438
Floor division composes: ⌊⌊n/a⌋/b⌋ = ⌊n/(ab)⌋, so every reachable argument has the form ⌊n / (2ᵃ·3ᵇ)⌋ (6 = 2·3 adds nothing new). There are only about 40 × 25 pairs (a, b), and many give the same quotient: exactly 438 states including 0. So the memo turns an exponential call tree (≈ 3^depth) into O(log² n) work. 1365 ignores the coincidences; a dense DP table of size n is impossible.
Practise more Trees, Graphs, Recursion and Dynamic Programming questionsTrees, Graphs, Recursion and Dynamic Programming: notes and key points
More Trees, Graphs, Recursion and Dynamic Programming questions
- Patience-sorting tails array for the longest STRICTLY increasing subsequence, and the length for the non-decreasing variant. What is…
- Weighted interval scheduling (start, end, value): DP over jobs sorted by end time with binary search for the last compatible job, versus…
- Broken-profile DP: number of ways to tile a 3 × n board with 1 × 2 dominoes, column by column with a 3-bit mask of cells already covered…
- Digit DP (position, running sum, tight flag) counts integers in [0, N] whose digits sum to 10, cross-checked by brute force. What is…
- All suffixes of 'banana' are inserted into a character trie (a suffix trie). What is printed (trie nodes including the root, distinct…
- BFS 2-colouring of each component of an undirected graph. What is printed (components, bipartite components)? python from collections…