Practice Problem

Word Search

Difficulty: Medium

Given an m x n grid of characters and a string word, determine if the word exists in the grid by following a path of adjacent cells (horizontally or vertically) without reusing any cell.

Word Search

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. The same letter cell may not be used more than once.

Examples

Example 1:

Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"
Output: true
Explanation: The path is A(0,0) → B(0,1) → C(0,2) → C(1,2) → E(2,2) → D(2,1)

Example 2:

Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "SEE"
Output: true
Explanation: The path is S(1,3) → E(2,3) → E(2,2)

Example 3:

Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCB"
Output: false
Explanation: The path A → B → C requires going back to B, but (0,1) is already used.

Constraints

  • m == board.length
  • n == board[i].length
  • 1 <= m, n <= 6
  • 1 <= word.length <= 15
  • board and word consist of only lowercase and uppercase English letters

Expected Complexity

  • Time: O(m * n * 3^L) where L is the length of the word. from each cell we branch into at most 3 directions (excluding where we came from)
  • Space: O(L). recursion depth equals the word length
MEDIUM
Arrays
Backtracking
Recursion
DFS
Algorithms
Intermediate

0 views

Solution

Hints

Hint 1
Hint 2
Premium
Hint 3
Premium
Hint 4
Premium