</>

212. Word Search II

Hard NeetCode 150
Tries Time O(S + M*N*3^L) Space O(S)
↗ Open on LeetCode Source: NeetCode 150

Quick review

Pattern
Tries
Time
O(S + M*N*3^L)
Space
O(S)

Standard Solution (C++)

SummaryGiven a 2D character board and a list of words, find all words from the list that can be formed by tracing a path of adjacent (horizontally or vertically neighboring) cells on the board, where each cell may be used at most once per word.

Approach
  • Build a Trie from all target words so that shared prefixes are traversed only once, and each terminal node stores the completed word.
  • DFS from every cell: for each board position, walk the Trie simultaneously, marking cells visited by temporarily overwriting them, then restoring after backtracking.
  • Prune eagerly: if the current cell has no Trie child for the current character, cut the search immediately; null out a Trie node's word pointer as soon as a word is found to avoid duplicates.
  • Optional pruning: delete leaf Trie nodes after a word is found so that already-exhausted branches are never re-entered, cutting runtime significantly on dense boards.
#include <vector>
#include <string>
#include <array>
using namespace std;

class Solution {
    // Trie node: 26 children + optional completed-word pointer
    struct TrieNode {
        array<TrieNode*, 26> ch{};
        string* word = nullptr;  // non-null at terminal nodes

        ~TrieNode() {
            for (TrieNode* c : ch) delete c;
        }
    };

    // Insert one word; store a pointer to the string at its terminal node
    void insert(TrieNode* root, string& s) {
        TrieNode* cur = root;
        for (char c : s) {
            int idx = c - 'a';
            if (!cur->ch[idx]) cur->ch[idx] = new TrieNode();
            cur = cur->ch[idx];
        }
        cur->word = &s;
    }

    // Returns true if the node has no live children (used for pruning)
    bool isLeaf(TrieNode* node) {
        for (TrieNode* c : node->ch)
            if (c) return false;
        return true;
    }

    // DFS: walk the board and the Trie in lockstep
    // Returns true if the parent should prune this child edge
    bool dfs(vector<vector<char>>& board, vector<string>& res,
             TrieNode* node, int r, int c) {
        int rows = board.size(), cols = board[0].size();
        if (r < 0 || r >= rows || c < 0 || c >= cols) return false;

        char ch = board[r][c];
        if (ch == '#' || !node->ch[ch - 'a']) return false;

        TrieNode* next = node->ch[ch - 'a'];

        if (next->word) {
            res.push_back(*next->word);
            next->word = nullptr;  // dedup: never collect this word again
        }

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

        // Explore 4 neighbors; collect prunable children
        static const int dr[] = {-1, 1, 0, 0};
        static const int dc[] = {0, 0, -1, 1};
        for (int i = 0; i < 4; ++i)
            dfs(board, res, next, r + dr[i], c + dc[i]);

        // Restore cell
        board[r][c] = ch;

        // Prune: if next is now a dead leaf, tell parent to drop the edge
        if (isLeaf(next) && !next->word) {
            delete next;
            node->ch[ch - 'a'] = nullptr;
            return true;
        }
        return false;
    }

public:
    vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
        TrieNode* root = new TrieNode();
        for (string& w : words) insert(root, w);

        vector<string> res;
        int rows = board.size(), cols = board[0].size();
        for (int r = 0; r < rows; ++r)
            for (int c = 0; c < cols; ++c)
                dfs(board, res, root, r, c);

        delete root;
        return res;
    }
};
Time O(S + M*N*3^L) where S = total characters across all words (Trie build), M*N = board cells, and L = max word length (each DFS step has at most 3 unvisited neighbors after the first step) Space O(S) for the Trie, plus O(L) recursion stack depth per DFS path

A canonical reference solution. Problem statement © LeetCode — see the official link above.

My Solution (C++)

#include <vector>
#include <string>
using namespace std;

class Solution {
public:
    struct TrieNode {
        TrieNode* children[26]={nullptr};
        // unique_ptr<TrieNode> children[26];
        string* word=nullptr;

        ~TrieNode(){
            for(int i=0; i<26; ++i){
                if(children[i]){
                    delete children[i];
                }
            }
        }
    };

    void insert(TrieNode* root, string& s){
        TrieNode* cur=root;
        for(char c: s){
            if(cur->children[c-'a']==nullptr){
                cur->children[c-'a']=new TrieNode();
            }
            cur=cur->children[c-'a'];
        }
        cur->word=&s;
    }

    void dfs(vector<vector<char>>& board, vector<string>& res, TrieNode* cur, int x, int y){
        if(x<0 || x>=board.size() || y<0 || y>=board[0].size()){
            return;
        }

        char c=board[x][y];
        if(c=='#' || !cur->children[c-'a']){
            return;
        }

        cur=cur->children[c-'a'];
        if(cur->word){
            res.push_back(*cur->word);
            cur->word=nullptr;
        }

        board[x][y]='#';
        int dx[4]={-1, 1, 0, 0};
        int dy[4]={0, 0, -1, 1};
        for(int i=0; i<4; ++i){
            dfs(board, res, cur, x+dx[i], y+dy[i]);
        }
        board[x][y]=c;
    }
    vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
        vector<string> res;

        TrieNode* root=new TrieNode();
        for(string& word: words){
            insert(root, word);
        }
        
        for(int x=0; x<board.size(); ++x){
            for(int y=0; y<board[0].size(); ++y){
                dfs(board, res, root, x, y);
            }
        }

        delete root;

        return res;
    }
};

// Time Complexity: O(S + M*N*3^L) where S is the total number of letters in the words, M and N are the dimensions of the board, and L is the maximum length of a word.
//                  O(S) to build the Trie, and O(M*N*3^L) for the DFS search.
// Space Complexity: O(S)
Time O(S + M*N*3^L) Space O(S)

My own solution and notes, as I wrote them.

▶ Run it — editable in-browser playground with a sample driver C++

Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.

C++ ▶ Runnable Auto-generated driver with sample input — unverified.

Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.

Related — same pattern