Ctrl K

Words Hidden in a Letter Grid

Hard
You are building a puzzle game. The m × n board grid holds one lowercase English letter per cell, and dictionary is a list of words. A word counts as found if you can trace it on the board: start at any cell and take each next letter from a cell that shares a side with the previous one (up, down, left or right). Diagonal moves are not allowed, and a single word may not use the same cell twice. Return every word from dictionary that can be traced on the board. List each found word once, in any order.
Example 1
grid=[['c', 'a', 't'], ['x', 'r', 'o'], ['d', 'o', 'g']], dictionary=['cat', 'car', 'rod', 'dog', 'tar', 'cart'] → ['cat', 'car', 'tar', 'rod', 'dog']

cat runs along the top row, car goes right then down, dog runs along the bottom row, rod goes down from r and then left, and tar goes left from t and then down. cart fails: no t touches the r.

Example 2
grid=[['a', 'b'], ['b', 'a']], dictionary=['aba', 'abab', 'aa'] → ['aba', 'abab']

aba and abab walk around the square. For aa the two a cells would have to touch, but they sit diagonally.

Example 3
grid=[['z']], dictionary=['zz'] → []

A cell cannot be reused, so a single z cannot spell zz.

Constraints
  • 1 ≤ m, n ≤ 12
  • grid[i][j] is a lowercase English letter
  • 1 ≤ len(dictionary) ≤ 3 · 10⁴
  • 1 ≤ len(dictionary[i]) ≤ 10, lowercase English letters only
  • All words in dictionary are distinct
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsEvery Way to Space the Words HardMirror Word Blocks HardWord Traced on a Letter Grid MediumComplete the Sudoku HardGlued Into a Palindrome Hard
loading Python…
Input
grid=[['c', 'a', 't'], ['x', 'r', 'o'], ['d', 'o', 'g']], dictionary=['cat', 'car', 'rod', 'dog', 'tar', 'cart']
Expected
['cat', 'car', 'tar', 'rod', 'dog']

Run checks the first 3 tests in your browser. Submit checks all 75 tests on the server, hidden ones included.