#212

Word Search II

Hard Trie-guided grid DFS

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Find every word from a list that can be traced in a letter grid by adjacent moves without reusing a cell.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: find all dictionary words in a letter grid.

Why this works: one trie for all the words; one DFS over the grid that follows trie edges, so dead ends stop early.

Example: words ["oath", "eat"] on a board

DFS from 'o' follows o → a → t → h → found "oath"from 'e' → a → t → found "eat"

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Adding the same word several times when it can be traced in more than one way.

Solve on LeetCode ↗
Complexity
  • Time: O(m·n·4·3^(L−1)) worst case, much faster with pruning.
  • Space: O(total characters in words).
Topic: Trie
🎬 Episode 97: video coming soon