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?
  1. A. True True True
  2. B. True False False
  3. C. True True False
  4. 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

Exams that ask this topic