Data Structures & AlgorithmsModerateTCS NQT · Infosys pattern
What is printed? (unique paths count with memoised recursion vs closed form)
What is printed? (unique paths count with memoised recursion vs closed form)
from functools import lru_cache
from math import comb
@lru_cache(None)
def up(r, c):
if r == 1 or c == 1: return 1
return up(r - 1, c) + up(r, c - 1)
print(up(3, 7), comb(8, 2), up(10, 10))- A. 21 28 48620
- B. 28 28 184756
- C. 28 28 48620
- D. 28 36 48620
Correct answer: C. 28 28 48620
An r × c grid needs (r − 1) downs and (c − 1) rights in some order: C(r + c − 2, r − 1). 3 × 7 → C(8, 2) = 28; 10 × 10 → C(18, 9) = 48620. Memoised recursion is O(r·c); without memoisation it is exponential.
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
- What is printed? (LIS length with O(n²) DP and the number of LIS) python a = [1, 3, 5, 4, 7] n = len(a); L = [1] n; C = [1] n for i in…
- What is printed? (coin change: number of combinations) python def ways(coins, amt): dp = [1] + [0] amt for c in coins: for a in range(c…
- What is printed? (rod cutting – maximise revenue) python price = [0, 1, 5, 8, 9, 10, 17, 17, 20] n = 8; r = [0] (n + 1) for j in range(1…
- What is printed? (subset sum with a boolean DP table) python a = [3, 34, 4, 12, 5, 2] def can(t): dp = [True] + [False] t for x in a: for…
- What is printed? (egg dropping: minimum trials in the worst case) python def trials(eggs, floors): # dp[m] = max floors checkable with m…
- What is printed? (0/1 knapsack with item reconstruction) python w = [1, 3, 4, 5]; v = [1, 4, 5, 7]; W = 7; n = 4 dp = [[0] (W + 1) for in…