Tutorialspoint
Problem
Solution
Submissions

Word Search II

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

Write a C program to find all words from a given dictionary that can be formed by sequentially adjacent letters on a 2D board. Letters can be used more than once, but each cell in a single word search cannot be used more than once. Use Trie data structure for efficient word searching.

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:
    • Build a Trie from the dictionary words.
    • For each cell in the board, start DFS to find words.
    • "eat" can be found starting from board[1][1] → board[1][2] → board[0][2].
    • "oath" can be found starting from board[0][0] → board[0][1] → board[1][1] → board[1][0].
Example 2
  • Input: board = [["a","b"],["c","d"]], words = ["abcb"]
  • Output: []
  • Explanation:
    • Build a Trie from the dictionary word "abcb".
    • Search for "abcb" on the board using DFS.
    • No valid path exists to form "abcb" without reusing cells.
    • Therefore, return empty result.
Constraints
  • m == board.length, n == board[i].length
  • 1 ≤ m, n ≤ 12
  • 1 ≤ words.length ≤ 3 * 10^4
  • 1 ≤ words[i].length ≤ 10
  • Time Complexity: O(M*N*4^L) where L is maximum word length
  • Space Complexity: O(ALPHABET_SIZE * N * L) for Trie
Trie AlgorithmsTCS (Tata Consultancy Services)Shopify
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

  • Build a Trie data structure from all dictionary words for efficient prefix checking
  • For each cell in the board, start a DFS traversal
  • During DFS, check if current path forms a valid prefix using the Trie
  • If a complete word is found, add it to the result
  • Use backtracking to explore all possible paths from each starting position
  • Mark visited cells during DFS and unmark them when backtracking

Steps to solve by this approach:

 Step 1: Create a Trie data structure to store all dictionary words efficiently.

 Step 2: Insert all words from the dictionary into the Trie for fast prefix lookup.
 Step 3: For each cell in the 2D board, start a Depth-First Search (DFS) traversal.
 Step 4: During DFS, move to adjacent cells and check if the path forms a valid prefix using Trie.
 Step 5: If a complete word is found (reach end of word in Trie), add it to result array.
 Step 6: Use backtracking by marking cells as visited during DFS and unmarking when returning.
 Step 7: Continue DFS from all possible starting positions to find all valid words.

Submitted Code :