Determine whether a word exists in a letter grid
AtlassianSoftware Engineer · Technical ScreenLast updated
Implement a backtracking search to determine if a target word can be formed by sequentially adjacent cells in a 2D character grid without reusing any cell.
Problem Statement
Given an m x n grid of characters board and a string word, return True if word exists in the grid, or False otherwise.
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 in a single word path.
Function Signature
def exist(board: list[list[str]], word: str) -> bool:
pass
Input and Output Format
- Input:
board: A list of lists of strings, where each element is a single character.word: A string consisting of English letters.
- Output: A boolean (
TrueorFalse).
Constraints
m == len(board)n == len(board[i])1 <= m, n <= 61 <= len(word) <= 15boardandwordconsist of only lowercase and uppercase English letters.
Examples
Example 1
board = [
['A', 'B', 'C', 'E'],
['S', 'F', 'C', 'S'],
['A', 'D', 'E', 'E']
]
word = "ABCCED"
# Output: True
Explanation: The path board[0][0] -> board[0][1] -> board[0][2] -> board[1][2] -> board[2][2] -> board[2][1] spells "ABCCED".
Example 2
board = [
['A', 'B', 'C', 'E'],
['S', 'F', 'C', 'S'],
['A', 'D', 'E', 'E']
]
word = "ABCB"
# Output: False
Explanation: The cell 'B' at (0, 1) cannot be reused to form the second 'B'.
Edge Cases to Consider
len(word) > m * n: Word length exceeds total available characters in the grid (immediateFalse).m == 1andn == 1: Grid contains a single cell.- A word with repeated identical characters where backtracking must properly restore visited state.
Hints
Hint 1
Iterate through every cell in the grid and initiate a depth-first search whenever a cell matches the first character of the word.
Hint 2
Use recursion to explore the four cardinal directions, marking the current cell as visited before recursing to prevent using it multiple times.
Hint 3
Restore the visited cell's original character or flag (backtrack) upon returning from the recursive call so subsequent paths can traverse it.
Follow-up questions
- How would you optimize the search if the letter frequency of the target word exceeds the frequency available on the board, or if the word's suffix is rarer than its prefix?
- How would you efficiently search for a list of thousands of words in the same board instead of just a single word?
- How does the time and space complexity change if diagonal moves are also permitted?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.