Word Search

35 min · exist()

A word on this board may bend around corners, but it may never cross its own tracks.

Given a rectangular character grid board and a string word, return true when one path through the grid spells the word from first character to last. Consecutive characters must occupy 4-directionally adjacent cells—cells that share a top, bottom, left, or right edge.

A path may use each cell at most once. Diagonal moves don't count, and the path can't leave the board. In the judge's char[][] wire format, every cell is a one-character string.

Constraints

  • 1 <= board.length <= 6
  • 1 <= board[row].length <= 6, and every row has the same length
  • 1 <= word.length <= 15
  • Board cells and word contain uppercase or lowercase English letters.

Hints

Try every starting cell

The first character may appear more than once. Start a search from each cell that matches word[0]; one successful path is enough.

Carry the next index

A search state needs a row, a column, and the index of the character being matched. From a match, try the four neighboring cells for the next index.

Mark, explore, restore

Temporarily replace the current cell with a marker that can't equal a letter. Search its neighbors, then restore the original character before returning. That blocks reuse without permanently changing the caller's board.

Follow-up

Before searching, how could character frequencies—or starting from the rarer end of the word—prune hopeless cases?

Visible cases

Examples

Example 1

ready
Input
board = [
  [
    "A",
    "B",
    "C",
    "E"
  ],
  [
    "S",
    "F",
    "C",
    "S"
  ],
  [
    "A",
    "D",
    "E",
    "E"
  ]
]
word = "ABCCED"
Expected
true
Why
the path turns through adjacent cells without reusing one

Example 2

ready
Input
board = [
  [
    "A",
    "B",
    "C",
    "E"
  ],
  [
    "S",
    "F",
    "C",
    "S"
  ],
  [
    "A",
    "D",
    "E",
    "E"
  ]
]
word = "SEE"
Expected
true
Why
a valid path starts at the S in the final column

Example 3

ready
Input
board = [
  [
    "A",
    "B",
    "C",
    "E"
  ],
  [
    "S",
    "F",
    "C",
    "S"
  ],
  [
    "A",
    "D",
    "E",
    "E"
  ]
]
word = "ABCB"
Expected
false
Why
finishing the word would require using the same B twice

Interview signal

Asked at

AmazonMetaMicrosoftBloomberg
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite