KatInterview

212. Word Search II

HardSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to find all words from a given dictionary that can be formed by traversing adjacent cells in a 2D character grid. Each cell can only be used once per word.

Solution

Word Search II in Python

class Solution:
    def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:
        # 1. Build Trie
        trie = {}
        for word in words:
            node = trie
            for char in word:
                node = node.setdefault(char, {})
            node['$'] = word  # Use '$' to mark the end of a word

        m, n = len(board), len(board[0])
        result = []

        def dfs(r, c, parent_node):
            char = board[r][c]
            curr_node = parent_node.get(char)

            # Pruning: if current path doesn't exist in Trie, stop.
            if not curr_node:
                return

            # Found a word
            word_found = curr_node.pop('$', None)
            if word_found:
                result.append(word_found) # No need to set to None, pop removes it

            # Mark cell as visited
            board[r][c] = '#'

            # Explore neighbors
            for dr, dc in [(0, 1), (0, -1), (1, 0), (-1, 0)]:
                nr, nc = r + dr, c + dc
                if 0 <= nr < m and 0 <= nc < n and board[nr][nc] != '#':
                    dfs(nr, nc, curr_node)
            
            # Backtrack
            board[r][c] = char

            # Pruning the Trie: remove leaf nodes
            if not curr_node: # If the node has no children and isn't an end-of-word
                parent_node.pop(char)

        # 2. DFS from each cell
        for r in range(m):
            for c in range(n):
                # Start DFS if the character is a potential start of a word
                if board[r][c] in trie:
                    dfs(r, c, trie)
        
        return result

Word Search II in Java

class Solution {
    // TrieNode class
    class TrieNode {
        TrieNode[] children = new TrieNode[26];
        String word = null;
    }

    private List<String> result;
    private int m, n;

    public List<String> findWords(char[][] board, String[] words) {
        result = new ArrayList<>();
        this.m = board.length;
        this.n = board[0].length;

        // 1. Build Trie
        TrieNode root = new TrieNode();
        for (String word : words) {
            TrieNode node = root;
            for (char c : word.toCharArray()) {
                int i = c - 'a';
                if (node.children[i] == null) {
                    node.children[i] = new TrieNode();
                }
                node = node.children[i];
            }
            node.word = word;
        }

        // 2. DFS from each cell
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                dfs(board, i, j, root);
            }
        }

        return result;
    }

    private void dfs(char[][] board, int r, int c, TrieNode node) {
        // Base cases for recursion termination
        if (r < 0 || r >= m || c < 0 || c >= n || board[r][c] == '#') {
            return;
        }

        char ch = board[r][c];
        TrieNode nextNode = node.children[ch - 'a'];

        // Pruning: if current path doesn't exist in Trie, stop.
        if (nextNode == null) {
            return;
        }

        // Found a word
        if (nextNode.word != null) {
            result.add(nextNode.word);
            nextNode.word = null; // Mark as found to avoid duplicates
        }

        // Mark cell as visited
        board[r][c] = '#';

        // Explore neighbors
        dfs(board, r + 1, c, nextNode);
        dfs(board, r - 1, c, nextNode);
        dfs(board, r, c + 1, nextNode);
        dfs(board, r, c - 1, nextNode);

        // Backtrack
        board[r][c] = ch;

        // Pruning the Trie: remove leaf nodes.
        // A node can be removed if it's not an end-of-word and has no children.
        if (nextNode.word == null) {
            boolean canPrune = true;
            for (TrieNode child : nextNode.children) {
                if (child != null) {
                    canPrune = false;
                    break;
                }
            }
            if (canPrune) {
                node.children[ch - 'a'] = null;
            }
        }
    }
}

Word Search II in C++

class Solution {
private:
    // TrieNode structure
    struct TrieNode {
        TrieNode* children[26];
        string word;

        TrieNode() : word("") {
            for (int i = 0; i < 26; i++) {
                children[i] = nullptr;
            }
        }
    };

    // Helper to build the Trie
    TrieNode* buildTrie(const vector<string>& words) {
        TrieNode* root = new TrieNode();
        for (const string& w : words) {
            TrieNode* node = root;
            for (char c : w) {
                int i = c - 'a';
                if (!node->children[i]) {
                    node->children[i] = new TrieNode();
                }
                node = node->children[i];
            }
            node->word = w;
        }
        return root;
    }

    vector<string> result;
    int m, n;

    void dfs(vector<vector<char>>& board, int r, int c, TrieNode* node) {
        // Base cases for recursion termination
        if (r < 0 || r >= m || c < 0 || c >= n || board[r][c] == '#') {
            return;
        }

        char ch = board[r][c];
        int idx = ch - 'a';

        // Pruning: if the current path doesn't exist in Trie, stop.
        if (!node->children[idx]) {
            return;
        }

        TrieNode* nextNode = node->children[idx];

        // Found a word
        if (!nextNode->word.empty()) {
            result.push_back(nextNode->word);
            nextNode->word = ""; // Mark as found to avoid duplicates
        }

        // Mark the cell as visited
        board[r][c] = '#';

        // Explore neighbors
        dfs(board, r + 1, c, nextNode);
        dfs(board, r - 1, c, nextNode);
        dfs(board, r, c + 1, nextNode);
        dfs(board, r, c - 1, nextNode);

        // Backtrack
        board[r][c] = ch;

        // Pruning the Trie: remove leaf nodes
        bool canPrune = true;
        for (int i = 0; i < 26; ++i) {
            if (nextNode->children[i] != nullptr) {
                canPrune = false;
                break;
            }
        }
        if (canPrune && nextNode->word.empty()) {
            node->children[idx] = nullptr;
            // In a real application, you might delete nextNode here,
            // but for LeetCode, setting to nullptr is sufficient to prune.
        }
    }

public:
    vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
        TrieNode* root = buildTrie(words);
        this->m = board.size();
        this->n = board[0].size();

        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                dfs(board, i, j, root);
            }
        }
        
        return result;
    }
};

Word Search II in TypeScript

function findWords(board: string[][], words: string[]): string[] {
    // TrieNode class definition
    class TrieNode {
        children: { [key: string]: TrieNode } = {};
        word: string | null = null;
    }

    // 1. Build Trie
    const root = new TrieNode();
    for (const word of words) {
        let node = root;
        for (const char of word) {
            if (!node.children[char]) {
                node.children[char] = new TrieNode();
            }
            node = node.children[char];
        }
        node.word = word;
    }

    const result: string[] = [];
    const m = board.length;
    const n = board[0].length;

    const dfs = (r: number, c: number, node: TrieNode) => {
        // Base cases for recursion termination
        if (r < 0 || r >= m || c < 0 || c >= n || board[r][c] === '#') {
            return;
        }

        const char = board[r][c];
        const nextNode = node.children[char];

        // Pruning: if current path doesn't exist in Trie, stop.
        if (!nextNode) {
            return;
        }

        // Found a word
        if (nextNode.word) {
            result.push(nextNode.word);
            nextNode.word = null; // Mark as found to avoid duplicates
        }

        // Mark cell as visited
        board[r][c] = '#';

        // Explore neighbors
        dfs(r + 1, c, nextNode);
        dfs(r - 1, c, nextNode);
        dfs(r, c + 1, nextNode);
        dfs(r, c - 1, nextNode);

        // Backtrack
        board[r][c] = char;
        
        // Pruning the Trie: remove leaf nodes.
        // A node can be removed if it's not an end-of-word and has no children.
        if (nextNode.word === null && Object.keys(nextNode.children).length === 0) {
            delete node.children[char];
        }
    };

    // 2. DFS from each cell
    for (let i = 0; i < m; i++) {
        for (let j = 0; j < n; j++) {
            dfs(i, j, root);
        }
    }

    return result;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.