MediumNo. 0079
Word Search — LeetCode 79 Python Solution
- Pattern
- Backtracking
- Topics
- Depth-First Search, Array, String, Backtracking, Matrix
- On study lists
- Blind 75, NeetCode 150, Grind 75 and Top Interview 150
- Reading time
- 3 min
- Source
- leetcode.com
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
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
| No. | Problem | Difficulty |
|---|---|---|
| 0212 | Word Search II | Hard |
| 0257 | Binary Tree Paths | Easy |
| 0949 | Largest Time for Given Digits | Medium |
| 0980 | Unique Paths III | Hard |
| 0988 | Smallest String Starting From Leaf | Medium |
| 1219 | Path with Maximum Gold | Medium |
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.