Word Search II - Problem

Given an m x n board of characters and a list of strings words, return all words on the board.

Each word must be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.

Input & Output

Example 1 — Basic Word Search
$ Input: board = [["o","a","a","n"],["e","t","a","e"],["i","h","k","r"],["i","f","l","v"]], words = ["oath","pea","eat","rain"]
Output: ["eat","oath"]
💡 Note: "eat" can be formed: e(1,0)→a(1,2)→t(1,1). "oath" can be formed: o(0,0)→a(0,1)→t(1,1)→h(2,1). "pea" and "rain" cannot be formed on this board.
Example 2 — Single Character Board
$ Input: board = [["a","b"],["c","d"]], words = ["abcb"]
Output: []
💡 Note: "abcb" cannot be formed because we cannot reuse the same cell. After a→b→c, we cannot go back to use 'b' again.
Example 3 — Multiple Short Words
$ Input: board = [["a","a"]], words = ["a","aa","aaa"]
Output: ["a","aa"]
💡 Note: "a" can be formed using either cell. "aa" can be formed using both cells a(0,0)→a(0,1). "aaa" cannot be formed as we only have 2 'a' characters.

Constraints

  • m == board.length
  • n == board[i].length
  • 1 ≤ m, n ≤ 12
  • board[i][j] is a lowercase English letter
  • 1 ≤ words.length ≤ 3 × 104
  • 1 ≤ words[i].length ≤ 10
  • words[i] consists of lowercase English letters
  • All the strings of words are unique

Visualization

Tap to expand
Word Search II - DFS Approach INPUT Character Board (4x4) o a a n e t a e i h k r i f l v Words to Find: "oath" "pea" "eat" "rain" ALGORITHM STEPS 1 Build Trie Insert all words into Trie * o e 2 DFS from each cell Start DFS at every position 3 Match with Trie Explore 4 directions 4 Collect Found Words Mark visited, backtrack FINAL RESULT Found Words Highlighted o a a n e t a e i h k r i f l v "oath" path "eat" path Output: ["eat", "oath"] OK - 2 words found! Key Insight: Using a Trie allows efficient prefix matching during DFS. We can prune search paths early when no word starts with current prefix. Time: O(M*N*4^L) where L is max word length. TutorialsPoint - Word Search II | DFS with Trie Approach
Asked in
Google 45 Amazon 38 Microsoft 32 Facebook 28
186.6K Views
High Frequency
~35 min Avg. Time
3.4K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen