KatInterview

Spell Words Along Connected Paths in a Letter Grid

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

Last updated

Tests backtracking DFS with trie-based pruning to find all words from a large list that can be traced through edge-adjacent, non-repeating cells in a 2-D letter grid.

You have an m x n grid of lowercase letters and a list of words to look up.

A word is traceable in the grid if you can find a sequence of cells whose letters match the word character by character, where every consecutive pair of cells shares an edge (up, down, left, or right), and no cell appears more than once in the same sequence.

Return all traceable words in ascending lexicographic order. If no word can be traced, return an empty list.

Rules

  • Two cells are adjacent only if they share an edge. Diagonal neighbours do not count.
  • Within the path for a single word, every cell must be distinct. Separate words may pass through the same cells.
  • If a word appears more than once in the input list, include it at most once in the output.

Constraints

  • 1 <= m, n <= 12, where m = len(board) and n = len(board[i]) for all rows i
  • Every board[i][j] is a single lowercase English letter ('a'–'z').
  • 1 <= len(words) <= 30000
  • 1 <= len(words[i]) <= 10, and every word consists of lowercase English letters.
  • The output must be sorted in ascending lexicographic (alphabetical) order.

Examples

Example 1

Input: locate_words([['c', 'a', 't'], ['r', 'o', 's'], ['e', 'd', 'g']], ['cat', 'cot', 'rod', 'red', 'dog', 'oat'])

Output: ['cat', 'oat', 'red', 'rod']

Example 2

Input: locate_words([['a', 'b'], ['c', 'd']], ['abdc', 'aba', 'abcd', 'a', 'a'])

Output: ['a', 'abdc']

Example 3

Input: locate_words([['a', 'a']], ['aaa'])

Output: []

Hints

Hint 1

Start with the single-word case: try every cell as a starting point and use backtracking DFS, temporarily marking each visited cell so it is not reused. Restore the cell when you backtrack.

Hint 2

Running an independent search per word is too slow for 30,000 words. Insert all words into a prefix tree (trie) first, then walk the grid and the trie together in one shared pass — a grid path that matches no trie prefix can be abandoned immediately.

Hint 3

Once a word is found, remove its end-marker from the trie so it is never reported twice. After backtracking, if a trie node is completely empty, delete it from its parent — this prunes dead branches and speeds up later searches.