Problem 79

Abstract / Summary

Given a grid of letters and a word check if the word can be formed by sequentially adjacent cells without reusing any cell.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0079.py

class Solution:
    def exist(self, board: List[List[str]], word: str) -> bool:
        def deeper(x, y, pos):
            current = word[pos]
            if board[y][x] != current:
                return False

            if pos == len(word) - 1:
                return True

            # footprints
            board[y][x] = ":"

            if x > 0               and deeper(x - 1, y, pos + 1):
                return True
            if x < len(board[y])-1 and deeper(x + 1, y, pos + 1):
                return True
            if y > 0               and deeper(x, y - 1, pos + 1):
                return True
            if y < len(board)-1    and deeper(x, y + 1, pos + 1):
                return True

            # no more footprints
            board[y][x] = current
            return False

        for y in range(len(board)):
            for x in range(len(board[y])):
                if board[y][x] == word[0] and deeper(x, y, 0):
                    return True

        return False
32 lines | 1032 bytes | submitted September 1, 2023 | GitHub   8% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 48% (5+ million submissions).

Typical patterns to solve this problem:
  • Array
  • Backtracking
  • Depth First Search
  • Matrix
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The implementation solves the classic word-search problem on a two-dimensional character grid. It determines whether a given word can be formed by sequentially adjacent cells-horizontally or vertically-without reusing any cell. The algorithm combines a depth-first search (DFS) with in-place marking to avoid extra memory structures.

Core Logic

The entry point iterates over every cell, launching a recursive search whenever the cell matches the first character of the target word.

for y in range(len(board)):
    for x in range(len(board[y])):
        if board[y][x] == word[0] and deeper(x, y, 0):
            return True
return False

The nested loops guarantee that every possible starting position is examined. The condition board[y][x] == word[0] filters out cells that cannot begin the word, reducing unnecessary recursion.

Recursive Search

The inner function deeper performs the DFS. It receives the current coordinates (x, y) and the index pos of the character being matched.

def deeper(x, y, pos):
    current = word[pos]
    if board[y][x] != current:
        return False

    if pos == len(word) - 1:
        return True

    board[y][x] = ":"

    if x > 0               and deeper(x - 1, y, pos + 1):
        return True
    if x < len(board[y])-1 and deeper(x + 1, y, pos + 1):
        return True
    if y > 0               and deeper(x, y - 1, pos + 1):
        return True
    if y < len(board)-1    and deeper(x, y + 1, pos + 1):
        return True

    board[y][x] = current
    return False

The function first checks whether the board cell matches the expected character. A mismatch aborts the current path immediately. When the last character of the word is successfully matched (pos == len(word) - 1), the function returns True, propagating success up the call stack.

In-Place Marking

To enforce the “no reuse” rule, the current cell is temporarily overwritten with a sentinel value (":"). This prevents subsequent recursive calls from stepping back onto the same cell.

board[y][x] = ":"

After exploring all four directions, the original character is restored, ensuring that other search paths can still use the cell.

board[y][x] = current

Directional Exploration

The four conditional calls explore left, right, up, and down neighbors. Boundary checks (x > 0, x < len(board[y])-1, y > 0, y < len(board)-1) guarantee that the recursion never accesses indices outside the board.

Each direction is evaluated in short-circuit fashion: as soon as a recursive call returns True, the function returns True without checking the remaining directions. This early exit avoids unnecessary work once a valid path is found.

Edge Cases Handled

The algorithm gracefully handles boards of any rectangular shape, including single-row or single-column configurations. The boundary checks prevent out-of-range errors even when the board dimensions are minimal.

When the target word consists of a single character, the condition pos == len(word) - 1 becomes true after the initial character match, causing an immediate True return without any recursion or marking.

If the board contains duplicate characters, the in-place marking ensures that a path cannot revisit a cell, even if the same character appears elsewhere. The restoration step guarantees that other independent paths can still use the cell after the current path backtracks.

An empty board or an empty word is implicitly handled: the outer loops will have zero iterations for an empty board, leading to a final False. An empty word would cause word[0] to raise an exception, but the problem specification typically guarantees a non-empty word, so the code aligns with that contract.

Performance Optimizations

The primary optimization is the avoidance of auxiliary data structures for visited tracking. By mutating the board directly, the algorithm reduces memory overhead and improves cache locality, as all state resides within the original grid.

Early termination is employed at multiple levels. The outer loop stops as soon as a successful start position is found. Within deeper, a mismatch aborts the current branch instantly, and a successful deeper call returns without exploring remaining directions.

The boundary checks are performed once per direction, eliminating the need for separate helper functions or repeated length calculations. This keeps the inner loop tight and minimizes Python attribute lookups.

Overall, the combination of in-place marking, early exits, and minimal per-call work yields an efficient traversal that scales well with typical board sizes and word lengths.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a large grid filled with tiles that each have a letter written on them. The goal is to find a secret word hidden inside this grid by connecting letters that are right next to each other.

The process starts by looking at every single tile on the board to see if it matches the very first letter of the target word. Once a match is found, the computer starts a hunt to find the rest of the letters.

To keep track of where the path has already gone, the computer temporarily changes the letter currently being used into a colon. This acts like putting down a little footprint so the computer does not try to use the exact same tile twice for the same word.

From the current spot, the computer looks in all four directions, which are left, right, up, and down, to see if the next letter of the word is waiting nearby. If it finds the next correct letter, it moves to that new spot and continues the search from there.

If the computer hits a dead end where none of the paths lead to the next letter, it performs a little clean-up. It turns that colon back into the original letter it found earlier. This is like lifting the footprint so that a different path through the grid can use that same spot later on.

The search keeps going until either the entire word is found safely or every possible path from that starting point has been checked. If the word is finished, the task is complete.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 7.00 | σ = 0.77

Complexity Analysis

Time: exponential
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java C# Rust JS Go TS
LeetcodeHelp C++ Python Java
MemoryLimitExceeded C++ Python
Progiez C++ Python Java
github aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++
bujosa Python
charles-wangkai Java
chenyanzhe C++
everthis JS
FelixFan1122 C#
fengvyi C++
fpdjsns C++
gaosq0604 Python
Garvit244 Python
gouthampradhan Java
halfrost Go
haoel C++
JoshCrozier JS
keineahnung2345 C++
lennylxx C
linouk23 C++
lkwq007 Python
luangong C++
MacJim C++
qiyuangong Python
ruoru Rust
shreymehul C#
suxrobGM C#
varunu28 Java
vli02 C
vthwang Java
XiaotaoGuo C++
yuanliu666 Kotlin
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, C#, Go, Java, JavaScript, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++, C++
bujosa Python
charles-wangkai Java
chenyanzhe C++
everthis JavaScript
FelixFan1122 C#
fengvyi C++
fpdjsns C++
gaosq0604 Python
Garvit244 Python
gouthampradhan Java
halfrost Go
haoel C++
JoshCrozier JavaScript
keineahnung2345 C++
lennylxx C
linouk23 C++
lkwq007 Python
luangong C++
MacJim C++
qiyuangong Python
ruoru Rust
shreymehul C#
suxrobGM C#
varunu28 Java
vli02 C
vthwang Java
XiaotaoGuo C++
yuanliu666 Kotlin
zfang399 C++
56 links | 39 authors | 10 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'Word Search - Backtracking - Leetcode 79 - Python'
NeetCode 11 mins
Word Search - Backtracking - Leetcode 79 - Python
YouTube video 'Word Search - Leetcode 79 - Recursive Backtracking (Python)'
Greg Hogg 13 mins
Word Search - Leetcode 79 - Recursive Backtracking (Python)
YouTube video '79. Word Search || Java || Leetcode || Hindi'
Coding Sphere 12 mins
79. Word Search || Java || Leetcode || Hindi
YouTube video 'Word Search - LeetCode 79 - JavaScript'
AlgoJS 8 mins
Word Search - LeetCode 79 - JavaScript
YouTube video 'Word Search - LeetCode 79 - Python (BACKTRACKING)'
Deepti Talesra 25 mins
Word Search - LeetCode 79 - Python (BACKTRACKING)
YouTube video '[Java] Leetcode 79. Word Search [Backtracking #11]'
Eric Programming 17 mins
[Java] Leetcode 79. Word Search [Backtracking #11]
YouTube video 'Leetcode | 79. Word Search | Medium | Java Solution'
Developer Docs 11 mins
Leetcode | 79. Word Search | Medium | Java Solution
YouTube video 'LeetCode 79. Word Search Explanation and Solution'
happygirlzt 9 mins
LeetCode 79. Word Search Explanation and Solution
YouTube video '79. Word Search | JavaScript | Depth First Search | LeetCode Daily Challenge | Detailed Explanation'
LeetCodeWithMonu 20 mins
79. Word Search | JavaScript | Depth First Search | LeetCode Daily Challenge | Detailed Explanation
YouTube video 'Word Search | Day 21 | Backtracking | [ July LeetCoding Challenge ] [ Leetcode #79 ] [ 2020 ]'
Algorithms Made Easy 5 mins
Word Search | Day 21 | Backtracking | [ July LeetCoding Challenge ] [ Leetcode #79 ] [ 2020 ]
YouTube video 'Daily Leetcode #1464: Apr 03, 2024 - 79. Word Search'
Programming Live with Larry 14 mins
Daily Leetcode #1464: Apr 03, 2024 - 79. Word Search
YouTube video 'Word Search in a 2D Grid using DFS Explained Step-by-Step | LeetCode 79 | Geekific'
Geekific 5 mins
Word Search in a 2D Grid using DFS Explained Step-by-Step | LeetCode 79 | Geekific
YouTube video '79. Word Search | April | Java | C++'
Mayur Programming Club 23 mins
79. Word Search | April | Java | C++
YouTube video 'LeetCode 79. Word Search 中文解释 Chinese Version'
happygirlzt 8 mins
LeetCode 79. Word Search 中文解释 Chinese Version
YouTube video 'Daily Leetcode #968: Nov 24, 2022 - 79. Word Search'
Programming Live with Larry 18 mins
Daily Leetcode #968: Nov 24, 2022 - 79. Word Search
YouTube video 'Leetcode 79 - Word Search (JAVA Solution Explained!)'
LC Bear 17 mins
Leetcode 79 - Word Search (JAVA Solution Explained!)
YouTube video 'Word Search - 79. LeetCode - Java'
Teddy Smith 18 mins
Word Search - 79. LeetCode - Java
YouTube video 'Leetcode 79. Word Search [ JAVASCRIPT ].'
Web Fusion with Bharadwaj 20 mins
Leetcode 79. Word Search [ JAVASCRIPT ].
YouTube video 'Word Search - Backtracking (DFS) - Leetcode 79 (Python) - Blind 75'
Matt Guest 13 mins
Word Search - Backtracking (DFS) - Leetcode 79 (Python) - Blind 75
YouTube video 'Leetcode 79. Word Search'
Algorithms Casts 25 mins
Leetcode 79. Word Search
20 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

30 solutions   September 1, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality