Imagine you have a large grid of letters and a dictionary of words. You want to find all the words from the dictionary that can be formed by tracing adjacent letters in the grid, like a word puzzle solver.
Given a 2D board of characters and a list of words, find 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.
1 <= board.length, board[i].length <= 121 <= words.length <= 3 * 10^41 <= words[i].length <= 10board and words consist of lowercase English letters
Edge cases: Empty board → returns empty listWords list empty → returns empty listWords with repeated letters requiring careful backtracking → correct detection
def findWords(board: List[List[str]], words: List[str]) -> List[str]:public List<String> findWords(char[][] board, String[] words)vector<string> findWords(vector<vector<char>>& board, vector<string>& words)function findWords(board, words)
def findWords(board: List[List[str]], words: List[str]) -> List[str]:
# Write your solution here
pass
class Solution {
public List<String> findWords(char[][] board, String[] words) {
// Write your solution here
return new ArrayList<>();
}
}
#include <vector>
#include <string>
using namespace std;
vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
// Write your solution here
return {};
}
function findWords(board, words) {
// Write your solution here
}
Common Bugs to Avoid
Wrong: Includes words that require diagonal adjacencyDFS explores diagonal neighbors incorrectly✅ Restrict DFS moves to only up/down/left/right directions
Wrong: Includes words that reuse the same cell multiple timesVisited cells not marked or unmarked properly during backtracking✅ Mark cell as visited before recursion and unmark after recursion returns
Wrong: Returns non-empty result on empty board or empty words listNo guard clauses for empty inputs✅ Add checks to return empty list if board or words list is empty
Wrong: Times out on large inputsBrute force search for each word without Trie pruning✅ Implement Trie to prune DFS paths and avoid redundant searches
Wrong: Includes words that skip letters or jump cellsBacktracking allows non-adjacent moves or skips visited marking✅ Ensure DFS only moves to adjacent cells and respects visited marking