KatInterview

Words Traced Through a Letter Board

Trees & GraphsAuto-graded · 16 test cases
MediumAuto-gradedTrees & Graphsbacktrackingtriedfs

Last updated

Find every dictionary word that can be traced through orthogonally adjacent cells of a letter board without reusing a cell, using backtracking guided by a prefix tree.

Words Traced Through a Letter Board

You are given a rectangular board of lowercase letters and a list of candidate words. Work out which candidates can be spelled by walking across the board.

A word can be spelled if there is a path of cells such that:

  • the letters along the path, in order, spell the word exactly;
  • each step moves to a cell directly above, below, left, or right of the current cell (diagonal steps are not allowed);
  • no cell appears more than once in the path for that word.

Different words are checked independently, so a cell used by one word may be used again by another.

Task

Implement collect_grid_words(board, candidates), which returns every candidate word that can be spelled on the board.

Output rules

  • Each word appears at most once in the result, even if it appears several times in candidates.
  • The result is sorted in ascending lexicographic order.
  • If no word can be spelled, return an empty list.
  • If the board is empty (no rows or no columns) or candidates is empty, return an empty list.
  • An empty-string candidate is never included.
  • Do not modify the input board.

Constraints

  • The board has M rows and N columns, with 1 <= M, N <= 10 (an empty board must still be handled gracefully).
  • All rows have the same length, and each cell holds a single character.
  • candidates has at most 1000 words.
  • Each word has length at most 10.

Examples

Example 1

Input: collect_grid_words([['a', 'b'], ['c', 'd']], ['ab', 'ad', 'ac'])

Output: ['ab', 'ac']

Example 2

Input: collect_grid_words([['a', 'e'], ['f', 'g']], ['aeg', 'af'])

Output: ['aeg', 'af']

Hints

Hint 1

Running a separate board search for every word repeats a lot of work when words share a beginning, such as 'oat' and 'oath'. Think about a structure that stores all words by their prefixes.

Hint 2

Build a prefix tree from the candidates, then run a depth-first search from every cell, moving only into neighbors whose letter continues a prefix in the tree. Temporarily mark the current cell as used and restore it when you backtrack.

Hint 3

Record a word when the current tree node ends one, and keep exploring since longer words may share it as a prefix. Store results in a set (or remove the word from the tree once found) to avoid duplicates, and sort at the end.