Word Search II
Detailed guide and Python implementation for the 'Word Search II' problem.
1. Concept Overview
The 'Word Search II' problem is a key challenge in the Trie section.
This implementation focuses on easy-level logic in Python.
We prioritize technical accuracy and code readability in our provided solutions.
2. Real-World Applications
3. Visual Intuition
Visualizing the logic flow for Word Search II.
4. Prerequisites
5. Step-by-Step Thinking
1. Understand the problem
Read the problem statement for Word Search II carefully.
2. Formulate brute force
Draft a simple iterative solution.
3. Identify inefficiency
Look for redundant calculations.
4. Optimize search path
Use hashing or sorting to speed up the process.
5. Final Implementation
Clean up the code for production standards.
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.
Write a function findWords(board: List[List[str]], words: List[str]) -> List[str].
- •m == len(board)
- •n == len(board[i])
- •1 <= m, n <= 12
- •board[i][j] is a lowercase English letter
- •1 <= len(words) <= 3 * 10^4
- •1 <= len(words[i]) <= 10
- •words consist of lowercase English letters
- •All the strings in words are unique
Examples
board = [["o","a","a","n"],["e","t","a","e"],["i","h","k","r"],["i","f","l","v"]], words = ["oath","pea","eat","rain"]
["oath","eat"]
The words "oath" and "eat" can be found on the board. "pea" and "rain" cannot.
board = [["a","b"],["c","d"]], words = ["abcb"]
[]
The word "abcb" requires using the 'b' cell twice, which is invalid.
Need a Hint?
Edge Cases to Watch
- Empty input structures
- Single element inputs
- Large numerical bounds
Ready to Solve?
Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.
Interview Insights & Variations
Complexity Analysis Breakdown
Why Time: Directly evaluates all possibilities.
Why Space: Uses standard local memory.
Why Time: Optimized paths reduce total operations.
Why Space: May trade memory for speed.
Optimized Solution Python Code
Optimized Solution Python Code
class TrieNode:
def __init__(self):
self.children = {}
self.isWord = False
def addWord(self, word):
curr = self
for c in word:
if c not in curr.children: curr.children[c] = TrieNode()
curr = curr.children[c]
curr.isWord = True
def find_words_opt(board, words):
root = TrieNode()
for w in words: root.addWord(w)
ROWS, COLS = len(board), len(board[0])
res, visit = set(), set()
def dfs(r, c, node, word):
if r < 0 or r == ROWS or c < 0 or c == COLS or (r, c) in visit or board[r][c] not in node.children:
return
visit.add((r, c))
node = node.children[board[r][c]]
word += board[r][c]
if node.isWord: res.add(word)
for dr, dc in [[0, 1], [0, -1], [1, 0], [-1, 0]]:
dfs(r + dr, c + dc, node, word)
visit.remove((r, c))
for r in range(ROWS):
for c in range(COLS):
dfs(r, c, root, "")
return list(res)Brute Force Code (Spoiler Guarded)
Brute Force Code (Spoiler Guarded)
def find_words_brute(board, words):
def exist(word):
ROWS, COLS = len(board), len(board[0])
def dfs(r, c, i, visited):
if i == len(word): return True
if r < 0 or c < 0 or r >= ROWS or c >= COLS or (r, c) in visited or board[r][c] != word[i]:
return False
visited.add((r, c))
res = any(dfs(r+dr, c+dc, i+1, visited) for dr, dc in [[1,0],[-1,0],[0,1],[0,-1]])
visited.remove((r, c))
return res
return any(dfs(r, c, 0, set()) for r in range(ROWS) for c in range(COLS))
return [w for w in words if exist(w)]Algorithm Pattern Checklist
When dealing with Trie data patterns.
Core Prerequisites
Revision Key Notes
Common Mistakes & Pitfalls
Related Questions
Recommended Python Resources
Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.
Python Loops
Learn how to use Python loops to iterate over data. Master for loops, while loops, break, continue, and loop best practices with interactive examples.
How to Sort a List in Python
Learn how to sort a list in Python using the sort() method and the sorted() function. Discover custom key sorting and reverse order examples.
Python String Methods
A complete reference guide for Python string manipulation. Master formatting, searching, splitting, replacing, and checking string properties.
Python vs JavaScript: Which Programming Language is Best?
A comprehensive comparison between Python and JavaScript. Explore syntax differences, performance, use cases (backend vs frontend), and coding examples.