SDE & MLE Prep

212. Word Search II

Problem

Given an m×n board of letters and a list of words, return every word that can be traced on the board through horizontally or vertically adjacent cells, using each cell at most once per word.

Example: board = ["oaan","etae","ihkr","iflv"], words = ["oath","pea","eat","rain"] → ["eat","oath"]

Constraints: board up to 12 × 12; up to 3·10⁴ words of length ≤ 10.

Put all words in a trie, then DFS from every cell following the trie — one traversal finds all words. Store the full word at its end node; clear it after finding (dedupe) and prune empty branches.

board  o a a n        trie of {oath, pea, eat, rain}
       e t a e        DFS from 'o': o -> a -> t -> h  ✓ "oath"
       i h k r        DFS from 'e': e -> a -> t       ✓ "eat"
       i f l v

Complexity: O(cells · 4 · 3^(L−1)) worst case, heavily pruned in practice.

class Solution:
    def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:
        root = {}
        for w in words:
            node = root
            for ch in w:
                node = node.setdefault(ch, {})
            node["$"] = w
        R, C, res = len(board), len(board[0]), []

        def dfs(r, c, parent):
            ch = board[r][c]
            node = parent[ch]
            if "$" in node:
                res.append(node.pop("$"))
            board[r][c] = "#"
            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 board[nr][nc] in node:
                    dfs(nr, nc, node)
            board[r][c] = ch
            if not node:
                parent.pop(ch)               # prune exhausted branch

        for r in range(R):
            for c in range(C):
                if board[r][c] in root:
                    dfs(r, c, root)
        return res