KatInterview

Region-Splitting Tree and Multi-Word Grid Search

Trees & GraphsModel answer
HardModel answerTrees & Graphsquadtreetriebacktracking

Last updated

Compress a square character grid into a four-way region tree, then locate a batch of words in the grid by walking neighbors in eight directions without reusing cells.

You are given a square grid of lowercase letters with side length N, where N is a power of 2 (up to 1024). This problem has two parts that share the same input.

Part 1: Compress the grid into a region tree

Represent the grid as a quadtree:

  • If every cell in a region holds the same letter, the region is a leaf that stores that letter.
  • Otherwise, the region is an internal node with four children, one for each equal quadrant: top-left, top-right, bottom-left, bottom-right.

Define a Node class holding the four child references and the letter (meaningful only for leaves). Implement buildQuadtree(grid), which returns the root.

Part 2: Find words in the grid

Given the same grid and a list of words, implement findWords(grid, words), which returns the words that can be spelled in the grid.

  • A word is spelled by a chain of cells, where each consecutive pair is adjacent horizontally, vertically, or diagonally (8 directions).
  • A single cell may not be used more than once within the same word.
  • Different words may reuse the same cells.

Constraints

  • N is a power of 2, N <= 1024.
  • The grid contains only lowercase English letters.
  • Up to 1000 words, each at most 20 characters long.

Example

grid = [['a', 'b'],
        ['c', 'd']]
# buildQuadtree(grid): an internal root with four leaf children (a, b, c, d)
# findWords(grid, ['ab', 'ad']) -> ['ab', 'ad']

What to cover

Explain your approach for both parts, give the time and space complexity, mention edge cases (empty input, empty strings, duplicate words, words that are prefixes of other words), and provide working code.

Hints

Hint 1

For the tree, avoid scanning a whole region to test whether it is uniform before splitting. Think about building the four quadrants first and deciding afterward whether they can be merged.

Hint 2

Running a separate search for each of up to 1000 words repeats the same path exploration. Consider storing all words in a prefix structure so one traversal of the grid serves every word at once.

Hint 3

While searching, mark the current cell as used and restore it on the way back. Also think about how to stop exploring prefixes whose words have all been found already.