Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA
Problem: Find the longest increasing path in a matrix (moving up/down/left/right to strictly larger values).
Problem: Find the longest increasing path in a matrix (moving up/down/left/right to strictly larger values).
from functools import lru_cache
def lip(m):
R, C = len(m), len(m[0])
@lru_cache(None)
def go(r, c):
best = 1
for nr, nc in ((r+1, c), (r-1, c), (r, c+1), (r, c-1)):
if 0 <= nr < R and 0 <= nc < C and m[nr][nc] > m[r][c]:
best = max(best, 1 + go(nr, nc))
return best
return max(go(r, c) for r in range(R) for c in range(C))
print(lip(((9, 9, 4), (6, 6, 8), (2, 1, 1))), lip(((3, 4, 5), (3, 2, 6), (2, 2, 1))))What is printed?- A. 4 5
- B. 3 4
- C. 4 4
- D. 5 4
Correct answer: C. 4 4
DFS with memoisation: strictly increasing moves cannot form cycles, so the grid is a DAG and each cell's answer is computed once. 1 → 2 → 6 → 9 and 3 → 4 → 5 → 6 both have length 4. O(R·C).
More Coding Interview Problems questions
- Problem: Find the cheapest way to cut a stick of length n at given positions; each cut costs the current piece's length. python from…
- Problem: Burst balloons; bursting balloon i earns left × a[i] × right with its current neighbours (1 beyond the ends). Maximise coins…
- Problem: Find the minimum number of intervals to remove so that the rest are non-overlapping – implemented with sort by START and keeping…
- Problem: Find the length of the longest valid (well-formed) parentheses substring. python def longestvalid(s): st, best = [-1], 0 for i…
- Problem: Return the number of provinces (connected components) from an adjacency matrix using DFS. java static int provinces(int[][] m) {…
- Problem: Find the town judge: trusted by everyone else and trusting nobody (−1 if none). python def judge(n, trust): score = [0] (n + 1)…