backtracking · Problem 2 of 2
Word Search
medium
Amazon
Google
Meta
Microsoft
Bloomberg
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 (horizontally or vertically neighboring). The same letter cell may not be used more than once in a single word path.
exist([
["A","B","C","E"],
["S","F","C","S"],
["A","D","E","E"]
], "ABCCED") -> true
exist([
["A","B","C","E"],
["S","F","C","S"],
["A","D","E","E"]
], "SEE") -> true
exist([
["A","B","C","E"],
["S","F","C","S"],
["A","D","E","E"]
], "ABCB") -> falseYour solution
Runs your code and animates it without grading anything. Change the input to see what it does on a case the tests do not cover.
Running is free — Submit is what records it. Or press ⌘↩
Tests
4 cases, 1 hidden| call | type | expected | result |
|---|---|---|---|
| exist([["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], "ABCCED") | word exists horizontally and vertically | true | — |
| exist([["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], "SEE") | word exists short | true | — |
| exist([["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], "ABCB") | reusing same cell invalid | false | — |
| withheld | hidden | withheld | — |
Hidden cases run too — their inputs aren't listed here, so aim for a general solution rather than one fitted to the cases above.
Complexity
- target time
- O(m × n × 4^L) where L is word length
- target space
- O(L) recursion depth
In-place cell marking provides O(1) auxiliary matrix space while backtracking.
Hints
Stuck? Hints open one at a time, each giving a little more away.
3 hints left