Taro Logo

Word Search

Medium
Asked by:
Profile picture
Profile picture
Profile picture
Profile picture
+29
More companies
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
1.7K views
Topics:
ArraysRecursion

Given an m x n grid of characters board and a string word, return true if word exists in the grid.

The word can 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.

Example 1:

Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"
Output: true

Example 2:

Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "SEE"
Output: true

Example 3:

Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCB"
Output: false

Constraints:

  • m == board.length
  • n = board[i].length
  • 1 <= m, n <= 6
  • 1 <= word.length <= 15
  • board and word consists of only lowercase and uppercase English letters.

Follow up: Could you use search pruning to make your solution faster with a larger board?

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the character set of the board? Can it contain lowercase letters, uppercase letters, or special characters?
  2. Are we guaranteed that the board and word inputs are non-empty?
  3. Can the same word appear multiple times on the board, and does it matter which path is found as long as any valid path returns true?
  4. Is the search case-sensitive, or should 'A' and 'a' be treated as matching?
  5. If the word length is greater than the total number of cells on the board (m * n), should we immediately return false?

Brute Force Solution

Approach

To solve this puzzle, the brute force approach involves exploring every possible path on the board, letter by letter, to see if we can spell out our target word. Since we do not know the correct path ahead of time, we simply try every single starting point and every possible direction from there.

Here's how the algorithm would work step-by-step:

  1. Scan the entire board to find any letter that matches the first letter of the word you are trying to spell.
  2. Once you find a matching letter, imagine standing on it and look at your immediate neighbors in all directions: up, down, left, and right.
  3. Choose one neighbor, step onto it, and check if it matches the next letter of the word.
  4. Continue walking from letter to letter, following every possible winding path across the board as long as the letters match the word you are building.
  5. If you ever hit a dead end where the surrounding letters do not match the next letter you need, or if you try to step onto a letter you already visited on this specific path, stop and step backward.
  6. Try a different direction from your previous spot to see where that path leads.
  7. Keep trying every possible combination of paths until you either successfully spell out the entire word or run out of paths to try.

Code Implementation

class Solution:n    def exist(self, board, word):n        row_count = len(board)n        col_count = len(board[0])nn        def backtrack(row_idx, col_idx, word_idx):n            if word_idx == len(word):n                return Truenn            if row_idx < 0 or row_idx >= row_count or col_idx < 0 or col_idx >= col_count or board[row_idx][col_idx] != word[word_idx]:n                return Falsenn            # Temporarily mark the current cell as visited by replacing its character with a null byte
            current_char = board[row_idx][col_idx]
            board[row_idx][col_idx] = '#'nn            # Explore all four orthogonal directions to find the next character in the target word sequence
            found_match = (n                backtrack(row_idx + 1, col_idx, word_idx + 1) orn                backtrack(row_idx - 1, col_idx, word_idx + 1) orn                backtrack(row_idx, col_idx + 1, word_idx + 1) orn                backtrack(row_idx, col_idx - 1, word_idx + 1)
            )nn            # Restore the cell to its original value so subsequent independent paths can use it
            board[row_idx][col_idx] = current_char
            return found_matchnn        for row_idx in range(row_count):n            for col_idx in range(col_count):n                if backtrack(row_idx, col_idx, 0):
                    return Truenn        return False

Big(O) Analysis

Time Complexity
O(M * N * 4^L) – To analyze the time complexity, let M and N be the dimensions of the board and L be the length of the word. We first scan the entire board of size M * N to find every possible starting cell that matches the first letter of the word. From each valid starting cell, we use a recursive depth-first search that branches out in up to 4 directions (up, down, left, right) for each subsequent letter in the word. This creates a worst-case recursive exploration tree of depth L with a branching factor of 4, leading to at most 4^L operations per starting cell. Multiplying the board traversal by the maximum path exploration yields approximately (M * N) * 4^L total operations, which simplifies to the Big O notation O(M * N * 4^L).
Space Complexity
O(L) – The auxiliary space is primarily determined by the recursion stack used to explore every possible winding path across the board letter by letter. In the worst-case scenario, the depth of this recursion stack grows linearly with the length of the target word, which we can denote as L. Additionally, the algorithm maintains state to prevent revisiting letters on the same path, but the memory consumed by these active recursive calls dominates the extra space usage. Therefore, the total extra memory scales linearly with the length of the word, simplifying to Big O of L.

Optimal Solution

Approach

The optimal strategy is like playing a word-hunting puzzle by exploring potential paths letter by letter. Whenever we find a matching letter on the board, we carefully venture out in all four directions to find the next letter of our target word, backing up to try a different path if we hit a dead end.

Here's how the algorithm would work step-by-step:

  1. Scan the entire grid from top to bottom, left to right, until you spot the very first letter of the target word.
  2. Once you find a matching starting letter, imagine placing a temporary marker on that spot so you know you have already visited it.
  3. Look at the immediate neighbors above, below, to the left, and to the right of your current position to see if any of them match the next letter in your target word.
  4. If you find a neighboring match, step over to that neighbor and repeat the search for the subsequent letter.
  5. If a path leads you to a dead end where the surrounding letters do not match what you need next, simply step backward to your previous location and try a different neighboring direction.
  6. If at any point you successfully step through every single letter of your target word in order, you can immediately celebrate success and stop searching.
  7. If you exhaust every possible path starting from your initial spot without success, remove the temporary marker and continue scanning the grid for another occurrence of the starting letter.

Code Implementation

class Solution:
    def exist(self, board_grid: list[list[str]], target_word: str) -> bool:
        row_count = len(board_grid)
        col_count = len(board_grid[0])

        def explore_path(current_row: int, current_col: int, word_index: int) -> bool:
            if word_index == len(target_word):
                return True

            if (
                current_row < 0 or current_row >= row_count or
                current_col < 0 or current_col >= col_count or
                board_grid[current_row][current_col] != target_word[word_index]
            ):
                return False

            # Temporarily mark the current cell as visited to prevent revisiting it in the same path.
            original_character = board_grid[current_row][current_col]
            board_grid[current_row][current_col] = '#'

            movement_deltas = [(-1, 0), (1, 0), (0, -1), (0, 1)]
            for row_delta, col_delta in movement_deltas:
                next_row = current_row + row_delta
                next_col = current_col + col_delta
                if explore_path(next_row, next_col, word_index + 1):
                    return True

            # Restore the original character so other starting paths can use this cell freely.
            board_grid[current_row][current_col] = original_character
            return False

        # Scan the grid to find a valid starting cell matching the first letter of the target word.
        for row_index in range(row_count):
            for col_index in range(col_count):
                if board_grid[row_index][col_index] == target_word[0]:
                    if explore_path(row_index, col_index, 0):
                        return True

        return False

Big(O) Analysis

Time Complexity
O(M * N * 4^L) – To analyze the time complexity, let M and N be the dimensions of the grid and L be the length of the target word. We scan the grid with a nested loop running M * N times to find the starting letter of the word. From each cell, the depth-first search explores up to 4 directions recursively for L levels. This results in at most M * N starting positions, each branching into a recursion tree of size 4^L, which simplifies to O(M * N * 4^L) operations.
Space Complexity
O(L) – The auxiliary space is primarily driven by the recursion stack used when exploring paths in the grid. In the worst-case scenario, the depth of the recursive calls corresponds to the length of the target word, which we can denote as L. Therefore, the maximum number of active stack frames at any given moment grows linearly with L. We also modify the grid in place or use a secondary structure of size proportional to L to track visited locations. Simplifying this to Big O notation yields O(L) auxiliary space.

Edge Cases

Empty board or empty word string
How to Handle:
Return false immediately as a valid path cannot be constructed from or within empty structures.
Single cell board matching a single letter word
How to Handle:
Return true because the base case correctly verifies the single character match without needing further recursion.
Word length exceeds the total number of cells on the board
How to Handle:
Return false early by comparing the word length against the total board area before starting the search.
Board contains all identical characters
How to Handle:
The backtracking visited set prevents reusing the exact same cell index within a single DFS path traversal.
Path requires revisiting the same cell in the same sequence
How to Handle:
Temporarily mutating the board cell or using a visited tracking mechanism prevents using the same cell more than once.
Extremely large grid exceeding recursion stack limits
How to Handle:
Iterative DFS or increasing stack depth may be necessary, though standard constraints usually fit within recursion limits.
No valid word path exists despite matching starting letters
How to Handle:
The backtracking algorithm naturally unwinds and explores all alternative directions before finally returning false.
Multiple valid paths exist for the same word
How to Handle:
The search short-circuits and returns true upon finding the very first successful complete match.
0/75 completed