Data Structures & AlgorithmsModerateProduct Company SDE · Amazon/Microsoft-style OA
Problem: Find whether a word exists in a letter grid by moving to adjacent (up/down/left/right) cells without reusing a cell.
Problem: Find whether a word exists in a letter grid by moving to adjacent (up/down/left/right) cells without reusing a cell.
def exist(g, w):
R, C = len(g), len(g[0])
def dfs(r, c, i):
if i == len(w): return True
if not (0 <= r < R and 0 <= c < C) or g[r][c] != w[i]: return False
tmp, g[r][c] = g[r][c], '#'
ok = any(dfs(r + dr, c + dc, i + 1) for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)))
g[r][c] = tmp
return ok
return any(dfs(r, c, 0) for r in range(R) for c in range(C))
g = [list("ABCE"), list("SFCS"), list("ADEE")]
print(exist(g, "ABCCED"), exist(g, "SEE"), exist(g, "ABCB"))What is printed?- A. True True True
- B. True False False
- C. True True False
- D. False True False
Correct answer: C. True True False
DFS with backtracking marks a cell '#' while it is on the current path and restores it afterwards. ABCB would need to reuse the B at (0,1), which is blocked by the mark. Worst case O(R·C·4^L).
More Coding Interview Problems questions
- Problem: List all combinations of k numbers from 1..n that sum to s (each number used at most once). python def combo(k, s, n=9): out = []…
- Problem: The recursive function below counts calls. How many times is f called for f(5)? python calls = 0 def f(n): global calls calls +=…
- Problem: Compute xⁿ by fast exponentiation (recursive squaring) and count multiplications. python mults = 0 def power(x, n): global mults…
- Problem: Generate the letter combinations a phone keypad number can represent and report how many there are. python from itertools import…
- Problem: Count set bits for each number 0..n using DP on the lowest bit. python def bits(n): r = [0] (n + 1) for i in range(1, n + 1)…
- Problem: Check whether a number is a power of two and isolate its lowest set bit. python print("; ".join(f"{x > 0 and x & (x - 1) == 0} {x…