One-Edit Word Lookup and Vertical Tree Traversal
Data Structure DesignModel answerLast updated
Design a data structure for single-character substitution queries, then output a binary tree's node values sorted by column, row, and left-to-right order.
Part A — Single-Substitution Word Index
Build a class with two methods:
build(words: List[str])— indexes a list of words.search(query: str) -> bool— returnsTrueif and only if some indexed word can be obtained by replacing exactly one character ofquery.
Rules and edge cases to address:
- Only single-character substitutions count. Insertions, deletions, and transpositions do not.
- Words of a different length than
querycan never match. - If
queryitself appears in the index, that alone is not a match — it needs a distinct neighbor that differs in exactly one position. - Duplicate entries in
wordsmust not produce false positives. - Words may contain characters outside lowercase ASCII; your design should handle this without relying on a fixed alphabet.
For your answer: describe at least two candidate designs, explain which you would implement and why, state time and space complexity for both build and search, and provide working code.
Part B — Binary Tree Nodes in Column-Row Order
You are given a binary tree whose nodes each hold a single lowercase letter. Coordinates are assigned as follows:
- The root is at
(row=0, col=0). - A left child inherits
(row+1, col−1). - A right child inherits
(row+1, col+1).
Return a single string formed by concatenating every node's character, sorted by:
- Column value, ascending.
- Row value, ascending within each column.
- Left-to-right tree order for nodes that share both row and column.
Example:
a
/ \
b c
/ \ \
d e f
Coordinates: a(0,0), b(1,−1), c(1,1), d(2,−2), e(2,0), f(2,2).
Output: "dbaefc"
Tie-breaking example: if a tree has both root.left.right and root.right.left, they both land at (row=2, col=0). The node reached via the left subtree should come first.
For your answer: describe your traversal strategy, explain how each sort criterion is satisfied, analyze time and space complexity, and provide working code.
Hints
Hint 1
For Part A, think about what two equal-length strings share when they differ in exactly one position. Can you turn that structural relationship into a hash key that lets you skip character-by-character comparisons at query time?
Hint 2
For Part A's correctness, consider how many distinct words you actually need to store per bucket to answer any query — you do not need the full word list, just enough to distinguish 'query is the only word here' from 'another distinct word is also here'.
Hint 3
For Part B, BFS naturally visits nodes level by level and left-to-right within each level, which matches two of the three sort criteria for free. Think about what data structure lets you collect characters per column as BFS runs, so you only need to emit columns in order at the end rather than sorting all nodes.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Part A: Single-Substitution Word Index
Clarifying the contract
Before writing any code, pin down the exact semantics:
search(query)isTrueiff some stored wordwsatisfieslen(w) == len(query)andwdiffers fromqueryin exactly one character position.- Storing
"hello"does not makesearch("hello")returnTrue. You need a distinct neighbor. - Storing
"hello"twice still only counts as one distinct word.
Design trade-offs
Brute force: compare query against every stored word character by character.
- Build: O(N·L) time and space.
- Search: O(N·L). Fine for a handful of words; hopeless at scale.
Neighbor generation: for each of the L positions in query, try all 25 other characters and check a hash set.
- Search: O(Σ·L) where Σ is alphabet size (25·L probes for lowercase).
- Breaks cleanly for lowercase but gets unwieldy for arbitrary Unicode.
Masked-pattern buckets (recommended): for each word w and each index i, generate the key (i, w[:i] + w[i+1:]). This is the word with position i erased, tagged with the erased index. Two equal-length strings that differ only at position i produce the same key, so they land in the same bucket. Using a tuple (int, str) as the key means no sentinel character can cause spurious collisions — this works for any character set.
Per bucket, store at most two distinct words. That is all you need: if a bucket holds two or more distinct words, then at least one of them is not query, and that word matches query everywhere except position i, so it differs by exactly one character.
- Build: O(N·L²) time (L keys per word, each key has length L−1). Space: O(N·L²) in the worst case, bounded by O(1) words per bucket.
- Search: O(L²) — build L keys and hash each one.
This is the right choice when the alphabet is unbounded or when search speed matters more than build time.
Trie with one-mismatch DFS: O(N·L) space, but O(Σ·L²) search in the worst case and more code to maintain. Worth mentioning as a memory-efficient alternative for very long words.
Why the bucket approach is correct
If stored word w differs from query exactly at position i, both produce key (i, shared_rest), so w is in the bucket we probe. Any word found in that bucket agrees with query at every position except possibly i. Excluding query itself leaves only words that differ in exactly one character. Deduplication via a set prevents a word inserted twice from faking the "two distinct words" condition.
Common mistakes
- Forgetting to exclude
queryitself from the bucket check. - Using a wildcard character like
*as a sentinel — collides if words can contain*. - Allowing repeated
buildcalls to accumulate state unintentionally.
Code
from typing import Dict, List, Set, Tuple
class OneEditDictionary:
def __init__(self) -> None:
self._buckets: Dict[Tuple[int, str], Set[str]] = {}
def build(self, words: List[str]) -> None:
self._buckets = {}
for w in words:
for i in range(len(w)):
key = (i, w[:i] + w[i + 1:])
bucket = self._buckets.setdefault(key, set())
if len(bucket) < 2:
bucket.add(w)
def search(self, query: str) -> bool:
for i in range(len(query)):
bucket = self._buckets.get((i, query[:i] + query[i + 1:]))
if not bucket:
continue
# True if there are ≥2 distinct words (one must differ from query),
# or if the single stored word is not query itself.
if len(bucket) >= 2 or query not in bucket:
return True
return False
Part B: Vertical Column-Row Tree Traversal
The three sort criteria and how to satisfy them
- Column ascending — emit buckets from
min_coltomax_col. - Row ascending within a column — append to buckets in BFS order; BFS visits all nodes at row
rbefore rowr+1. - Left-to-right for ties — within a row, BFS dequeues parents left-to-right and enqueues each node's left child before its right child, preserving lateral order throughout.
BFS handles criteria 2 and 3 automatically. No explicit sort is needed — just collect into per-column lists as BFS runs, then concatenate from min_col to max_col.
Why BFS beats collect-and-sort here
A DFS with (col, row, sequence_number, char) tuples followed by sorting also works and is worth mentioning, but it costs O(n log n) and requires extra bookkeeping for the sequence number. BFS is O(n) time and O(n) space, handles skewed trees without recursion-depth concerns, and the left-to-right tie-break is a structural guarantee rather than something you have to engineer.
Tie-breaking argument
Two nodes at the same (row, col) share a lowest common ancestor. One lives in its left subtree, the other in the right. BFS finishes the entire left subtree's contribution to any given row before the right subtree's, because the left child is enqueued first. A stable column bucket therefore lists the left-subtree node before the right-subtree node with no extra work.
Complexity
- Time: O(n) — each node is enqueued and dequeued exactly once.
- Space: O(n) — the queue holds at most one full level (up to n/2 nodes), and the column buckets together hold all n characters.
Edge cases
- Empty tree: return
"". - Single node: one bucket, one character.
- Perfectly skewed tree of depth n: iterative BFS avoids O(n) call-stack depth that a recursive DFS would incur.
Code
from collections import defaultdict, deque
from typing import Optional
class TreeNode:
def __init__(
self,
val: str,
left: "Optional[TreeNode]" = None,
right: "Optional[TreeNode]" = None,
) -> None:
self.val = val
self.left = left
self.right = right
def vertical_order_string(root: Optional[TreeNode]) -> str:
if root is None:
return ""
# columns maps col -> list of chars in (row asc, left-to-right) order
columns: dict[int, list[str]] = defaultdict(list)
min_col = max_col = 0
# queue entries: (node, col)
queue: deque[tuple[TreeNode, int]] = deque()
queue.append((root, 0))
while queue:
node, col = queue.popleft()
columns[col].append(node.val)
min_col = min(min_col, col)
max_col = max(max_col, col)
if node.left:
queue.append((node.left, col - 1))
if node.right:
queue.append((node.right, col + 1))
return "".join(
"".join(columns[c]) for c in range(min_col, max_col + 1)
)
Verification against the example
Tree: a(0,0), b(1,−1), c(1,1), d(2,−2), e(2,0), f(2,2)
BFS visits in order: a, b, c, d, e, f
Buckets: {-2: ['d'], -1: ['b'], 0: ['a','e'], 1: ['c'], 2: ['f']}
Output: "d" + "b" + "ae" + "c" + "f" → "dbaefc" ✓