← Back to Codes

2026-06-09 16:36:42

Word Search II in Python and Java | LeetCode #212

Learn how to solve Word Search II in Python and Java with beginner-friendly explanation, step-by-step dry run, custom examples, and time complexity.

Word Search II in Python and Java

In this tutorial, we will learn LeetCode #212: Word Search II in very simple language. We will understand the idea step by step, see custom examples, and write complete code in Python and Java.

What Is the Word Search II Problem?

This problem asks us to solve a common coding interview task using the given input. The goal is to return the correct result without using a slow brute force method.

For this problem, we will use trie and backtracking because it gives a clean and optimized solution.

Example input:
board = [["o","a"],["t","h"]], words = ["oa","hat","to"]

Expected result:
Output: ["oa"]

Explanation:
Only oa can be formed.

Beginner-Friendly Idea

The main idea is to avoid trying every possible answer blindly. Instead, we keep useful information while reading the input and use that information to make the next decision.

At each step, ask: “What do I already know, and how does the current value change my answer?”

Using our example:
board = [["o","a"],["t","h"]], words = ["oa","hat","to"]

Approach:
trie and backtracking

We update variables step by step until we reach:
Output: ["oa"]

Why Do We Use This Approach?

A direct brute force solution is usually easier to think about, but it can become slow when the input is large. The optimized approach keeps only the important state and avoids repeated work.

That is why trie and backtracking is useful for this problem.

Step-by-Step Explanation

Let us dry run the algorithm using a custom example.

Step 1
Use this custom example.

board = [["o","a"],["t","h"]], words = ["oa","hat","to"]

We will solve it using trie and backtracking.

Step 2
Look at the first important value from the example and create the variables needed by the algorithm.

current_state = based on the first value
answer = not finished yet

Step 3
Move to the next useful value and update the state.

The algorithm compares the new value with the old state.
If the new value improves the answer, we update the answer.

Step 4
Continue this process until all useful values are processed.

After processing the example, we get:

Output: ["oa"]

Why?
Only oa can be formed.

Important Code Logic

The most important part is updating the algorithm state after reading each useful value. This is where the answer becomes better step by step.

Think like this:

old_state = what we knew before
current_value = value we are checking now
new_state = updated result after using current_value

For our example, the final state gives:
Output: ["oa"]

Example 1

Input:
board = [["o","a"],["t","h"]], words = ["oa","hat","to"]

Output:
Output: ["oa"]

Explanation:
Only oa can be formed.

Example 2

Input:
board = [["a","b"],["c","d"]], words = ["ab","ac","bd"]

Output:
["ab","ac"]

Explanation:
Only words that can be formed by neighboring cells are returned.

Python Code

Here is the complete Python solution for LeetCode #212.

class TrieNode:
    def __init__(self):
        self.children = {}
        self.word = None


class WordSearchTwoFinder:
    def find_words(self, board, words):
        root = TrieNode()
        for word in words:
            node = root
            for char in word:
                node = node.children.setdefault(char, TrieNode())
            node.word = word

        rows = len(board)
        cols = len(board[0])
        result = []

        def dfs(row, col, node):
            if row < 0 or col < 0 or row == rows or col == cols:
                return

            char = board[row][col]
            if char == "#" or char not in node.children:
                return

            next_node = node.children[char]
            if next_node.word:
                result.append(next_node.word)
                next_node.word = None

            board[row][col] = "#"
            dfs(row + 1, col, next_node)
            dfs(row - 1, col, next_node)
            dfs(row, col + 1, next_node)
            dfs(row, col - 1, next_node)
            board[row][col] = char

        for row in range(rows):
            for col in range(cols):
                dfs(row, col, root)

        return result


board = [["c", "a", "t"], ["r", "r", "e"], ["d", "o", "g"]]
words = ["cat", "car", "dog", "red"]
finder = WordSearchTwoFinder()
print(finder.find_words(board, words))  # Output includes: ['cat', 'car', 'dog']

Java Code

Here is the complete Java solution for LeetCode #212.

import java.util.ArrayList;
import java.util.List;

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

class WordSearchTwoFinder {
    public List<String> findWords(char[][] board, String[] words) {
        TrieNode root = new TrieNode();
        for (String word : words) {
            TrieNode node = root;
            for (char ch : word.toCharArray()) {
                int index = ch - 'a';
                if (node.children[index] == null) node.children[index] = new TrieNode();
                node = node.children[index];
            }
            node.word = word;
        }

        List<String> result = new ArrayList<>();
        for (int row = 0; row < board.length; row++) {
            for (int col = 0; col < board[0].length; col++) {
                dfs(board, row, col, root, result);
            }
        }
        return result;
    }

    private void dfs(char[][] board, int row, int col, TrieNode node, List<String> result) {
        if (row < 0 || col < 0 || row == board.length || col == board[0].length) return;

        char ch = board[row][col];
        if (ch == '#' || node.children[ch - 'a'] == null) return;

        TrieNode nextNode = node.children[ch - 'a'];
        if (nextNode.word != null) {
            result.add(nextNode.word);
            nextNode.word = null;
        }

        board[row][col] = '#';
        dfs(board, row + 1, col, nextNode, result);
        dfs(board, row - 1, col, nextNode, result);
        dfs(board, row, col + 1, nextNode, result);
        dfs(board, row, col - 1, nextNode, result);
        board[row][col] = ch;
    }

    public static void main(String[] args) {
        char[][] board = {{'c','a','t'}, {'r','r','e'}, {'d','o','g'}};
        String[] words = {"cat", "car", "dog", "red"};
        WordSearchTwoFinder finder = new WordSearchTwoFinder();
        System.out.println(finder.findWords(board, words));
    }
}

Time and Space Complexity

Time Complexity: O(n)

The time complexity depends on how many values the algorithm needs to process and whether it uses sorting, binary search, heap, or traversal.

Space Complexity: O(n)

The extra space is used for the variables or data structures needed by the optimized approach.

Final Summary

LeetCode #212: Word Search II becomes easier when we break it into small steps. First understand what the problem asks, then track the important state, dry run with an example, and finally write the code.