Chat app~40 min2s · 256 MBtarget O(cells × 3^(L - 1)) time, O(N × L × 26) spaceclassic twin: lc-212trie · backtracking
A chat app has a word game. Players see a grid of letters, and they spell words by moving from a letter to a letter next to it: up, down, left or right. A cell may be used only once in one word.
The app has a dictionary of valid words. After each round, it must list every dictionary word that was hidden in the grid, so that the score screen can show what the players missed.
Write find_words(grid, dictionary).
grid is a list of rows of lowercase letters, all of the same length.dictionary is a list of different lowercase words.Input: grid = ["tar", "ode", "sky"], dictionary = ["tad", "toad", "sky", "dot", "yes", "ode", "oar"]
Output: ["dot", "ode", "sky", "tad"]The trie of the dictionary has 20 nodes below its root. A walk from every cell makes 42 calls, and 27 of them stop at once because the trie has no child for the letter.
| Step | What happens | Words found |
|---|---|---|
| [1] | Build the trie of 7 words | |
| [5] | Walk from t at the top left: t, then a, then d below it spells tad |
tad |
| [5] | Walk from o in the middle row: o, d, e along the row spells ode |
ode |
| [5] | Walk from d in the middle: d, o, t spells dot |
dot |
| [5] | Walk from s at the bottom left: s, k, y spells sky |
sky |
| [6] | toad fails because o and a are not neighbours, and yes and oar fail too. Sort |
dot, ode, sky, tad |
Input: grid = ["ab", "cd"], dictionary = ["abdc", "abcd", "ba", "bad"]
Output: ["abdc", "ba"]The walk a, b, d, c turns twice, and is allowed.
The word abcd needs b next to c, which is a diagonal move. The word bad needs a next to d, also a diagonal.
Input: grid = ["aa"], dictionary = ["aaa", "a", "aa"]
Output: ["a", "aa"]The grid has two cells, so a word of three letters cannot be spelled without reusing a cell.
1 ≤ rows, columns ≤ 81 ≤ len(dictionary) ≤ 2000, and every word has 1 to 8 lowercase lettersFrom one cell there are at most 4 moves, then at most 3 more at each step. An 8-letter walk from a cell has up to 4 × 3^6 = 2,916 shapes, and there are 64 cells. That is under 200,000 walks for one word.
With 2,000 words, searching for each word alone costs hundreds of millions of steps. A trie of all the words lets one walk check every word at once, and stop as soon as no word starts that way.