Region-Splitting Tree and Multi-Word Grid Search
Trees & GraphsModel answerLast 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
Nis 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.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Overview
The two parts exercise different skills. Part 1 is divide and conquer, where the goal is to avoid rescanning cells. Part 2 is backtracking, where the key improvement is to search for all words at once using a prefix tree (trie) and prune it as words are found.
Part 1: Building the quadtree
Approach: bottom-up recursion.
- Base case: a 1x1 region is a leaf holding that cell's letter.
- Otherwise, recursively build the four quadrants (each of half the side length).
- If all four results are leaves with the same letter, collapse them into one leaf. Otherwise return an internal node with the four children.
Why it is correct: a region is uniform exactly when all four quadrants are uniform and share one letter. By induction on region size, a leaf means "one letter throughout" and an internal node means "at least two different letters".
Complexity:
- A naive "scan the region, then split" approach costs O(N²) per level over log N levels, so O(N² log N).
- The bottom-up version does constant work per visited node. T(n) = 4T(n/2) + O(1) gives O(N²) total, since there are about 4N²/3 nodes visited.
- Space: recursion depth is log N (about 10 for N = 1024), plus the output tree, which can reach O(N²) nodes for a checkerboard-like grid.
Common mistakes: rescanning regions at every level; forgetting to merge only when all four children are leaves (an internal child can never be merged); mixing up row and column offsets for the quadrants.
Part 2: Finding the words
Naive approach: run a DFS from every cell for each word. With 1000 words this repeats the same exploration for shared prefixes ("car", "cart", "care") and wastes time on paths that no word could use.
Better approach: trie plus one DFS per starting cell.
- Insert every non-empty word into a trie. Store the full word at the node where it ends, which doubles as an end marker.
- From each cell whose letter is a child of the trie root, run a DFS that walks the grid and trie together.
- At each step, if the current trie node holds a word, record it and remove it from the node so it is reported once.
- Mark the current cell as visited by temporarily overwriting it (for example with
#), explore the 8 neighbors whose letters are children of the current trie node, then restore the cell. - Pruning: after exploring a node, if it has no children and no stored word, delete it from its parent. Prefixes whose words are all found are never explored again, and the search can stop once the trie is empty.
Why it is correct: the DFS enumerates every simple path (no repeated cell) whose letters spell a prefix of some word. A word is present exactly when some such path reaches its end marker. Restoring the cell on backtrack guarantees one use per cell per path. Pruning only removes branches with no unfound words, so no result is lost.
Complexity: let S be the total characters across all words and L the maximum word length.
- Trie build: O(S).
- Search worst case: O(N² · 8 · 7^(L-1)), since after the first step at most 7 unvisited neighbors remain. In practice the trie bounds both depth and branching, and pruning shrinks it further.
- Space: O(S) for the trie plus O(L) recursion depth (at most 20).
Edge cases
- Empty grid or empty word list: return
[]. - Empty strings in
words: skip. - Duplicate words: report once.
- Single-letter words: found when the DFS lands on a matching cell.
- A word that is a prefix of another (for example "ab" and "abc"): handled because the end marker can sit on an internal trie node.
- The grid is modified during the search but fully restored afterward.
- Output order: return words in order of first appearance in the input.
Code (Python)
from typing import List, Optional
class Node:
def __init__(self, val=None, is_leaf=False,
top_left=None, top_right=None,
bottom_left=None, bottom_right=None):
self.val = val
self.is_leaf = is_leaf
self.top_left = top_left
self.top_right = top_right
self.bottom_left = bottom_left
self.bottom_right = bottom_right
def buildQuadtree(grid: List[List[str]]) -> Optional[Node]:
n = len(grid)
if n == 0:
return None
def build(r, c, size):
if size == 1:
return Node(grid[r][c], True)
h = size // 2
tl = build(r, c, h)
tr = build(r, c + h, h)
bl = build(r + h, c, h)
br = build(r + h, c + h, h)
if (tl.is_leaf and tr.is_leaf and bl.is_leaf and br.is_leaf
and tl.val == tr.val == bl.val == br.val):
return Node(tl.val, True)
return Node(None, False, tl, tr, bl, br)
return build(0, 0, n)
DIRS = [(-1, -1), (-1, 0), (-1, 1), (0, -1),
(0, 1), (1, -1), (1, 0), (1, 1)]
def findWords(grid: List[List[str]], words: List[str]) -> List[str]:
if not grid or not grid[0] or not words:
return []
rows, cols = len(grid), len(grid[0])
root = {}
for w in words:
if not w:
continue
node = root
for ch in w:
node = node.setdefault(ch, {})
node['$'] = w
found = set()
def dfs(r, c, parent):
ch = grid[r][c]
node = parent[ch]
w = node.pop('$', None)
if w is not None:
found.add(w)
grid[r][c] = '#'
for dr, dc in DIRS:
nr, nc = r + dr, c + dc
if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] in node:
dfs(nr, nc, node)
grid[r][c] = ch
if not node:
del parent[ch]
for r in range(rows):
for c in range(cols):
if not root:
break
if grid[r][c] in root:
dfs(r, c, root)
return [w for w in dict.fromkeys(words) if w in found]
For the example grid, buildQuadtree returns an internal node with four distinct leaves, and findWords(grid, ['ab', 'ad']) returns ['ab', 'ad'], with "ad" found via the diagonal move.
Possible follow-ups
- Use the quadtree to speed up queries, for example skipping uniform regions that cannot contain a needed letter.
- For very large grids, run the per-cell DFS in parallel, merging results at the end (the trie pruning then needs per-thread copies or a different dedupe strategy).
- Replace dict-based trie nodes with arrays of 26 entries to reduce overhead.