Tutorialspoint
Problem
Solution
Submissions

Word Search II

Certification: Advanced Level Accuracy: 0% Submissions: 0 Points: 20

Write a C++ program to implement Word Search II to find all words from a dictionary that can be formed by sequentially adjacent letters on a grid.

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:
    • "eat" and "oath" can be formed using adjacent cells.
Example 2
  • Input: board = [['a','b'], ['c','d']]
    words = ["abcb","ab","cd","ac","bd"]
  • Output: ["ab","ac","bd","cd"]
  • Explanation:
    • "abcb" cannot be formed without reusing letters.
Constraints
  • 1 ≤ m, n ≤ 12
  • 1 ≤ words.length ≤ 3×10⁴
  • Each word has max length 10
  • All board letters and words are lowercase
  • Time Complexity: O(m*n*4^L) where L is the maximum word length
  • Space Complexity: O(total characters in words)
Trie AlgorithmsAmazonMicrosoft
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use a Trie data structure to store all the words for efficient prefix matching
  • Implement a depth-first search (DFS) to explore all possible paths on the board
  • Track visited cells during the search to avoid using the same cell twice
  • Optimize by pruning search paths that cannot form any word in the dictionary
  • Use a set to store found words to avoid duplicates

Steps to solve by this approach:

 Step 1: Build a Trie from the words list
 Step 2: For each board cell, run DFS
 Step 3: Track prefix path in Trie and visited cells
 Step 4: On reaching a word in Trie, add it to the result
 Step 5: Mark visited cells and restore after DFS
 Step 6: Avoid duplicates by marking found words in Trie

Submitted Code :