← Whiteboard questions

Word Search II

Find every word from a list hidden in a letter grid

DSA, Hard, Tries

Which structure or algorithm, and what does it cost.

A grid board is a list of equal-length strings of lowercase letters. A list words holds distinct lowercase words. A word is in the grid if you can trace its letters through cells that touch side by side (up, down, left, right), using each cell at most once for that word. Return every word from words that is in the grid, in alphabetical order. List each found word one time. If no word is in the grid, return an empty list.

Examples

Input board = ["cat", "oxe", "dgs"], words = ["cog", "cat", "tax", "eat", "gods", "cot", "xe"]
Output ["cat", "tax", "xe"]
Why cat runs along the top row. tax goes t, a, x. cog fails because g does not touch o.
Input board = ["ab", "cd"], words = ["abdc", "acdb", "abc", "bad", "dcba", "abcd"]
Output ["abdc", "acdb"]
Why abdc and acdb walk around the square. abc fails because b and c only touch diagonally.
Input board = ["aa", "aa"], words = ["aaaaa", "aaaa", "a", "aab"]
Output ["a", "aaaa"]
Why a cell cannot be used twice, so five a letters do not fit in four cells.

Constraints

Your answer must contain

Target Aim to search the grid once for all words together, not once for each word.

Hints

Try the problem first. Open one hint at a time.

Hint 1 a nudge

One grid search per word repeats a lot of work, because many words start with the same letters. Can you search for all the words at once?

Hint 2 the approach

Put all the words in a tree of letters. Walk the grid and the tree together, so one step in the grid is one step down the tree.

Hint 3 the key step

Move only to neighbours matching a child in the tree. Mark cells on the path and undo the mark when you step back. Record a word at its end node.

Walkthrough

Full walkthrough brute force to best

Brute force

For each word, search the grid on its own: try every cell as the start and follow neighbours that match the next letter, never reusing a cell on the path. One word costs up to about R * C * 3^L steps for an R by C grid and word length L, since after the first step a path has at most three new neighbours. With W words, the total is W times that. Words that share a start repeat the same walks.

Best method

Build a trie from all the words, and store each whole word on its end node. Then run a depth-first search from every cell whose letter is a child of the trie root. At a cell, move to the matching trie child. If that node holds a word, record it and clear it, so it is never recorded twice. Mark the cell as used, try the four neighbours whose letter is a child of the current node, then restore the cell. After the neighbours are done, if the node has no children left, remove it from its parent, so dead branches are never walked again. This is correct because every path the search takes spells a start of some word, a cell is never used twice on one path, and every word in the grid is a path that the search tries from its first cell. One walk serves every word that shares those letters.

Hand trace

Run on example 1. Build the trie from cog, cat, tax, eat, gods, cot, xe. Start at c (row 0, col 0): c is a child of the root. Go to o below it: the trie has co, but its next letters are g and t, and the neighbours of o are d and x, so that path stops. Go to a at (0, 1), then t at (0, 2): t carries cat, so record cat and remove the dead branch. Start at t (0, 2): go to a, then to x below it: the node carries tax, so record tax. Start at x (1, 1): go to e at (1, 2): the node carries xe, so record xe. Starts at e and g find no matching neighbour. Sorted, the result is ["cat", "tax", "xe"].

Code

def find_words(board, words):
    grid = [list(row) for row in board]
    rows, cols = len(grid), len(grid[0])
    root = {}
    for w in words:
        node = root
        for ch in w:
            node = node.setdefault(ch, {})
        node["$"] = w
    found = []
    def dfs(r, c, parent):
        ch = grid[r][c]
        node = parent[ch]
        if "$" in node:
            found.append(node.pop("$"))
        grid[r][c] = "#"
        for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
            nr, nc = r + dr, c + dc
            if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] in node:
                dfs(nr, nc, node)
        grid[r][c] = ch
        if not node:
            del parent[ch]
    for r in range(rows):
        for c in range(cols):
            if grid[r][c] in root:
                dfs(r, c, root)
    return sorted(found)

Time and memory

In the worst case the time is O(R * C * 3^L), because a path has at most 3 new neighbours after its first step and at most L steps. The search time has no factor W: a path stops at the first letter that is not the start of any word. Building the trie takes O(total letters of all words). Memory is O(total letters of all words) for the trie, O(R * C) for the grid copy and O(L) for the recursion.

Common mistakes

  • Searching the grid separately for every word. With 2,000 words this repeats the same walks and is far too slow.
  • Not restoring a cell after the recursive call. A later path then cannot use that cell, and words are missed.
  • Recording the same word twice when two paths spell it. Clear the word from its node after the first find. But do not return after a find: a longer word can continue from the same node, so keep going to the neighbours.
  • Returning the words in the order they were found. The answer must be in alphabetical order.

Related problems

More Tries problems
Word Search II: hints, walkthrough and Python solution