Data Structures & AlgorithmsEasyTCS NQT Digital · Product Company SDE
Problem: Find the minimum path sum from the top-left to the bottom-right of a cost grid (moves: right or down).
Problem: Find the minimum path sum from the top-left to the bottom-right of a cost grid (moves: right or down).
def minpath(g):
R, C = len(g), len(g[0])
for r in range(R):
for c in range(C):
if r == 0 and c == 0: continue
up = g[r-1][c] if r else float('inf')
left = g[r][c-1] if c else float('inf')
g[r][c] += min(up, left)
return g[-1][-1]
print(minpath([[1, 3, 1], [1, 5, 1], [4, 2, 1]]))What is printed?- A. 8
- B. 6
- C. 7
- D. 11
Correct answer: C. 7
Each cell adds the cheaper of its top and left neighbours. Best route 1 → 3 → 1 → 1 → 1 = 7. A greedy walk that always steps to the cheaper next cell would go down to 1, then right to 5… and pay more. O(R·C), done in place.
More Coding Interview Problems questions
- Problem: Count the ways to decode a digit string where 'A' = 1 … 'Z' = 26. python def decode(s): prev2, prev1 = 1, (1 if s[0] != '0' else…
- Problem: Decide whether a string can be split into words from a dictionary. python def wb(s, words): W = set(words); dp = [True] + [False]…
- Problem: Return the maximum product of a contiguous subarray (values may be negative or zero). python def maxprod(a): hi = lo = best =…
- Problem: Can an array be split into two subsets with equal sums? python def cansplit(a): s = sum(a) if s % 2: return False reach = 1 for x…
- Problem: Return the length of the longest palindromic subsequence (not substring). python def lps(s): n = len(s); dp = [[0] n for in…
- Problem: Multiply a chain of matrices with dimensions given as p (matrix i is p[i−1] × p[i]) using the fewest scalar multiplications…