Data Structures & AlgorithmsHardGoogle · Flipkart interview
Problem: Length of the longest strictly increasing path in a matrix (moves in 4 directions), with memoised DFS.
Problem: Length of the longest strictly increasing path in a matrix (moves in 4 directions), with memoised DFS.
from functools import lru_cache
m = [[3, 4, 5], [3, 2, 6], [2, 2, 1]]
R, C = len(m), len(m[0])
@lru_cache(None)
def dfs(r, c):
best = 1
for x, y in ((r+1, c), (r-1, c), (r, c+1), (r, c-1)):
if 0 <= x < R and 0 <= y < C and m[x][y] > m[r][c]:
best = max(best, 1 + dfs(x, y))
return best
print(max(dfs(r, c) for r in range(R) for c in range(C)))What is printed?- A. 5
- B. 4
- C. 6
- D. 3
Correct answer: B. 4
The chain 3 → 4 → 5 → 6 (top row, then down to 6) has length 4; 2 at (1,1) → 4 → 5 → 6 ties it. No 5-step chain exists because every cell adjacent to the starts of these chains is not smaller. Memoisation makes each cell's answer computed once: O(R·C).
More Coding Interview Problems questions
- Problem: Smash stones pairwise (x ≤ y leaves y − x) until at most one remains; minimise the final weight. Equivalent to splitting into two…
- Problem: You may swap a[i] with b[i] at any indices. Find the minimum swaps making BOTH arrays strictly increasing (DP with 'swapped at i'…
- Problem: Remove every interval that is covered by another interval ([a, b] is covered by [c, d] if c ≤ a and b ≤ d); count those that…
- Problem: Delete the fewest characters from a string of a's and b's so that no 'b' comes before an 'a'. python def mindel(s): bseen = dels…
- Problem: Add two 32-bit integers without + or −, using XOR for the sum and AND-shift for the carry; Python needs explicit masking to…
- Problem: Validate a byte sequence as UTF-8 (a 1-byte char starts 0xxxxxxx; an n-byte char starts with n 1s and a 0, followed by n − 1…