TIC
The Interns Company

Word Search II

HardAcceptance: 36.8%

Problem Statement

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.

Constraints:

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

Input Format:

  • An m x n grid of characters 'board'
  • An array of strings 'words'

Output Format:

  • Return an array of all words from the input list that can be found on the board

Examples:

Example 1:

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"]

Explanation:

The words 'eat' and 'oath' can be constructed from the board.

Example 2:

Input:

board = [["a","b"],["c","d"]], words = ["abcb"]

Output:

[]

Explanation:

The word 'abcb' cannot be constructed from the board because the same letter 'b' would be used twice.

Solutions

Trie + Backtracking DFS

Time: O(m*n*4^L)
Space: O(sum of word lengths)

Use a Trie data structure to store all the words, then perform backtracking DFS from each cell on the board to find words that exist in the Trie.

Optimized Trie + Backtracking

Time: O(m*n*4^L)
Space: O(sum of word lengths)

An optimized version that prunes the Trie as words are found to reduce search space and improve efficiency.

Algorithm Walkthrough

Example input: nums = []

Step-by-step execution:

  1. Build a Trie with all the words: oath, pea, eat, rain
  2. Start DFS from cell (0,0) containing 'o'
  3. Follow path: o → a → t → h, which spells 'oath'
  4. Add 'oath' to result
  5. Continue searching from other cells...
  6. From cell (1,0) containing 'e', follow path: e → a → t, which spells 'eat'
  7. Add 'eat' to result
  8. Return ['oath', 'eat']

Hints

Hint 1
Use a Trie data structure to efficiently store and search for words.
Hint 2
Implement backtracking DFS from each cell in the board.
Hint 3
Optimize by pruning search paths that cannot lead to valid words in the Trie.

Video Tutorial

Video tutorials can be a great way to understand algorithms visually

Visualization

Visualize the Trie structure and the backtracking process on the grid.

Key visualization elements:

  • current cell
  • visited cells
  • path
  • trie structure

Implementation Notes

This problem combines Trie data structure with backtracking search. The key optimization is using a Trie to efficiently check prefixes and find words during the search.