Data Structures & AlgorithmsModerateInfosys SP/DSE · Product Company SDE
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 bottom-up.
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 bottom-up.
def tri(t):
dp = t[-1][:]
for row in reversed(t[:-1]):
dp = [x + min(dp[i], dp[i + 1]) for i, x in enumerate(row)]
return dp[0]
print(tri([[5], [9, 6], [4, 6, 8], [0, 7, 9, 5]]))What is printed?- A. 18
- B. 24
- C. 20
- D. 16
Correct answer: A. 18
Bottom-up, each cell becomes its value plus the better of its two children: row 2 → 4, 13, 13; row 1 → 9 + 4 = 13, 6 + 13 = 19; top → 5 + 13 = 18 (path 5, 9, 4, 0). Greedy top-down picks 6 over 9 and ends with 5 + 6 + 6 + 7 = 24. O(n²) time, O(n) space.
More Coding Interview Problems questions
- 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…
- Problem: Compare the longest common SUBSTRING (contiguous) with the longest common SUBSEQUENCE of two log fragments. python def lcsub(a…