Word Search II
HardNeetCode 150Top Interview 150 TriesSnowflakeCiscoTwo SigmaZoomProblem
You are given a grid of lowercase letters and a list of words. A word is on the board if you can spell it by starting at some cell and repeatedly stepping to a neighbouring cell (up, down, left or right), using each cell at most once per word.
Return every word from the list that is on the board, in any order. Each word appears once in the result.
Constraints
- 1 ≤ rows, columns ≤ 12
- 1 ≤ words.length ≤ 3 · 10⁴, and every word has 1 to 10 lowercase letters
- All words in the list are different
Examples: pick one to animate
Solutions
Time: Each of the m·n cells starts a search that follows a trie path of length at most L, and after the first step each cell has at most 3 unvisited neighbours to try.
Space: The trie holds each letter of each word once; the recursion and the in-place board marks use only O(L) extra.
Put all the words in a trie, then walk the board once. From every cell, step along the trie as you step
across the board: if the trie has no child for the cell's letter, stop at once (this prunes almost everything).
Mark the cell with # while it is on the current path and restore it afterwards. When you reach a
node that stores a whole word, add that word to the answer and erase it from the node so it is reported only once.