
Problem
Solution
Submissions
Word Search II using Trie
Certification: Advanced Level
Accuracy: 100%
Submissions: 1
Points: 15
Write a Java program to find all words in a given board of characters. The words can be constructed from letters of adjacent cells (horizontally, vertically, or diagonally), and each letter cell can only be used once in a word. You are given a 2D board of characters and a list of words to find.
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: For "oath", we can find it by starting at board[0][0] ('o') and moving to adjacent cells: 'a' at [0][1], 't' at [1][1], and 'h' at [2][1]. For "eat", we can find a path through adjacent cells.
Example 2
- Input:
board = [
['a','b'],
['c','d'] ]
words = ["abcd","abad","acbd","abdc"] - Output: ["abcd"]
- Explanation: We can find "abcd" by starting at board[0][0] ('a'), then 'b' at [0][1], then 'c' at [1][0], and finally 'd' at [1][1].
Constraints
- 1 <= board.length, board[i].length <= 12
- board[i][j] is a lowercase English letter
- 1 <= words.length <= 3 * 10^4
- 1 <= words[i].length <= 10
- All words in the input list are unique
- Time Complexity: O(M * N * 4^L), where M and N are the dimensions of the board and L is the maximum length of a word
- Space Complexity: O(K), where K is the total number of characters in all words
Editorial
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. |
Solution Hints
- Build a Trie data structure from the list of words to search for
- Use a depth-first search (DFS) starting from each cell in the board
- During DFS, match characters on the board with nodes in the Trie
- Use a visited matrix to avoid reusing the same cell for a single word
- When a complete word is found, add it to the result set
- Use a set to avoid adding duplicate words to the result
- Optimize by pruning the Trie as words are found