Data Structures & AlgorithmsModerateTCS NQT Digital · Product Company SDE
Problem: Find the minimum sum of a falling path through a square grid: start anywhere in the top row and move to one of the (up to) three cells diagonally/directly below.
Problem: Find the minimum sum of a falling path through a square grid: start anywhere in the top row and move to one of the (up to) three cells diagonally/directly below.
def falling(m):
n = len(m); prev = m[0][:]
for i in range(1, n):
prev = [m[i][j] + min(prev[max(j - 1, 0):j + 2]) for j in range(n)]
return min(prev)
print(falling([[4, 1, 6], [5, 8, 2], [3, 9, 7]]), falling([[-2, 5], [4, -3]]))What is printed?- A. 10 -5
- B. 9 -5
- C. 9 2
- D. 6 -5
Correct answer: B. 9 -5
dp for row i, column j = m[i][j] + min of the up-to-three cells above (the slice handles the borders). Row 1: 6, 9, 3; row 2: 3 + 6 = 9, 9 + 3 = 12, 7 + 3 = 10 → 9 (path 4 → 5 → 3, or 1 → 5 → 3). Second grid: −2 → −3 = −5. O(n²) time, O(n) space.
More Coding Interview Problems questions
- Problem: Minimum path sum from the top of a number triangle to the bottom (step to the same index or index + 1 in the next row), computed…
- Problem: Pairs (a, b) with a < b can be chained when the next pair's a is strictly greater than the previous b. Find the longest chain…
- Problem: Paint a row of houses with 3 colours so that neighbours differ; costs[i] = cost of each colour for house i. Minimise the total…
- Problem: Split an integer n ≥ 2 into at least two positive parts to maximise the product of the parts. python def intbreak(n): dp = [0, 1]…
- Problem: A cable of length n is cut into pieces; prices[k − 1] is the price of a piece of length k. Maximise revenue (unbounded knapsack)…
- Problem: Count subsets of distinct-position items whose values sum exactly to the target (0/1 counting knapsack with a 1-D array iterated…