Tries
106 / 170TriesLesson 3 of 4About 59 min
The payoff. You solved the grid search one unit ago; the trie is what makes it work for many words at once.
You have a grid of letters and a list of words, and you must report which words can be traced through adjacent cells without reusing a cell.
You solved the single-word version in Unit 10. The obvious extension is to run that search once per word, which is correct and costs the full grid search multiplied by the number of words. With a large dictionary that is far too slow.
The search is Unit 10's grid backtracking with one extra parameter and one extra guard. The guard is worth seeing on its own, because it is where all the saving comes from.
Below, no search runs at all. Every cell of a small board is simply asked whether any word in the dictionary could begin there.
board = [["o", "a"], ["e", "t"]]words = ["oat", "oa", "ate", "zzz"] first_letters = {word[0] for word in words} # the root's children for row in range(len(board)): for col in range(len(board[0])): letter = board[row][col] verdict = "worth starting" if letter in first_letters else "nothing begins here" print(f"({row}, {col}) holds {letter!r}: {verdict}")This problem is the reason Tries follows Backtracking rather than sitting elsewhere in the course. Neither technique alone solves it: the backtracking explores the grid and the trie decides which explorations are worth doing.
Before starting, write down the grid search you already know, then add the trie node as a parameter and the child lookup as the first guard. Framed that way it is a modification rather than a new problem.
Running the single-word grid search once per word, for w words on an m by n grid, where each search explores up to four directions for up to L steps. What is the time, and what extra space does the trie version add?
for word in words: for row in range(rows): for col in range(cols): if exists(grid, row, col, word, 0): found.append(word) breakRead the constraints first and let them tell you what complexity is expected. Derive the approach, implement it, run the tests, and submit when it passes.