MediumNo. 0079

Word Search — LeetCode 79 Python Solution

Topics
Depth-First Search, Array, String, Backtracking, Matrix
Reading time
3 min

The problem

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.

Example

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

Python solution

PythonSolution
class Solution:
    def exist(self, board: List[List[str]], word: str) -> bool:
        def dfs(i: int, j: int, k: int) -> bool:
            if k == len(word) - 1:
                return board[i][j] == word[k]
            if board[i][j] != word[k]:
                return False
            c = board[i][j]
            board[i][j] = "0"
            for a, b in pairwise((-1, 0, 1, 0, -1)):
                x, y = i + a, j + b
                ok = 0 <= x < m and 0 <= y < n and board[x][y] != "0"
                if ok and dfs(x, y, k + 1):
                    return True
            board[i][j] = c
            return False

        m, n = len(board), len(board[0])
        return any(dfs(i, j, 0) for i in range(m) for j in range(n))

Complexity

Time
O(m × n × 3k)
Space · auxiliary
O(min(m × n, k))

Pattern: Backtracking

Build candidates one choice at a time and abandon a branch the moment it cannot work. LeetCode 79. Word Search is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Backtracking.

The backtracking guide has the Python template for the pattern and the 105 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0212Word Search IIHard
0257Binary Tree PathsEasy
0949Largest Time for Given DigitsMedium
0980Unique Paths IIIHard
0988Smallest String Starting From LeafMedium
1219Path with Maximum GoldMedium

Frequently asked questions

How hard is LeetCode 79. Word Search?

LeetCode 79. Word Search is rated Medium on LeetCode.

What is the time complexity of LeetCode 79. Word Search?

The Python solution on this page runs in O(m × n × 3k).

What is the space complexity of LeetCode 79. Word Search?

The Python solution on this page uses O(min(m × n, k)) auxiliary space.

What topics does LeetCode 79. Word Search cover?

LeetCode 79. Word Search is tagged Depth-First Search, Array, String, Backtracking and Matrix on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.