KatInterview

Dictionary Words Hidden in a Letter Grid

Trees & GraphsAuto-graded · 18 test cases
HardAuto-gradedTrees & Graphstriebacktrackingdfs

Last updated

Find every dictionary word that can be traced through adjacent, non-repeating cells of a letter grid, which rewards sharing prefixes across words instead of searching per word.

You are given a rectangular grid of lowercase letters and a list of lowercase words. Write a function that returns every word from the list that can be traced in the grid.

A word is traceable if you can pick a starting cell and then repeatedly step to a horizontally or vertically adjacent cell so that the letters you visit, in order, spell the word. Diagonal steps are not allowed. A single cell cannot be used twice within the spelling of one word. Different words may reuse the same cells.

Input

  • grid: a list of m rows, each a list of n single-character lowercase strings.
  • dictionary: a list of lowercase strings. It may contain duplicates.

Output

A list of strings containing each traceable word exactly once, even if the word appears several times in dictionary or can be traced along several different paths. The order of the returned words does not matter. If nothing can be traced, return an empty list.

The dictionary can be large, so checking each word with its own full grid search is too slow. Aim for a solution that shares work between words with common prefixes.

Constraints

  • 1 <= m, n <= 12
  • 1 <= len(dictionary) <= 30000
  • 1 <= len(dictionary[i]) <= 10
  • Every word and every grid cell contains only lowercase English letters.

Examples

Example 1

Input: search_grid_dictionary([['o', 'a', 'a', 'n'], ['e', 't', 'a', 'e'], ['i', 'h', 'k', 'r'], ['i', 'f', 'l', 'v']], ['oath', 'pea', 'eat', 'rain'])

Output: ['oath', 'eat']

Example 2

Input: search_grid_dictionary([['a', 'b'], ['c', 'd']], ['ab', 'ac', 'bd', 'abcd'])

Output: ['ac', 'ab', 'bd']

Hints

Hint 1

Searching the grid once per word repeats the same prefix walks many times. Think about a structure that stores all the words together so shared prefixes are stored once.

Hint 2

Build a prefix tree from the dictionary, then run a single backtracking DFS from every cell while descending the prefix tree in step with the grid. Stop as soon as the current letter has no matching child.

Hint 3

To avoid duplicates, clear the end-of-word marker once its word is reported. To speed things up, delete prefix-tree nodes that have no children and no word left after exploring them.