One-Edit Typo-Tolerant Word Index
Medium · Coding & Algorithms · Software Engineer · Onsite
Problem Statement
Implement a typo-tolerant lookup service over a fixed vocabulary of unique strings. Given a word list dictionary, a word w in dictionary matches a query string whenever the Levenshtein edit distance between query and w is 0 or 1 — meaning query is either identical to w or can be transformed into w via a single character insertion, a single character deletion, or a single character substitution. (Swapping two adjacent characters is not a single operation under Levenshtein distance and costs 2 edits.)
Build a FuzzyIndex class optimized for fast repeated lookups, along with the judge entry point fuzzy_keyword_index(dictionary, operations, arguments):
FuzzyIndex.__init__(self, dictionary: List[str]): Indexes the unique strings indictionaryonce upfront.FuzzyIndex.search(self, query: str) -> List[str]: Returns every matching word fromdictionarywithin edit distance1ofquery, preserving their original order indictionary.fuzzy_keyword_index(dictionary, operations, arguments): InstantiatesFuzzyIndex(dictionary)and executes each operation inoperationswith the matching argument list inarguments(where"search"passes[query]), returning the list of outputs.
Examples
Example 1
- Input:
dictionary = ["stone", "store", "tone", "storm", "plum"]operations = ["search", "search", "search"]arguments = [["store"], ["ston"], ["stnoe"]]
- Output:
[["stone", "store", "storm"], ["stone"], []] - Explanation:
- Searching
"store"matches"stone"(1substitution:'r' -> 'n'),"store"(0edits), and"storm"(1substitution:'e' -> 'm'), returned indictionaryorder ("stone"appears before"store")."tone"needs2edits (delete's'and'r' -> 'n'). - Searching
"ston"matches"stone"via1insertion ('e'). - Searching
"stnoe"differs from"stone"at two positions ('n'and'o'swapped), which takes2Levenshtein edits and returns[].
- Searching
Example 2
- Input:
dictionary = ["mint", "min", "pint", "mist"]operations = ["search", "search"]arguments = [["min"], ["planets"]]
- Output:
[["mint", "min"], []] - Explanation:
"min"is1insertion away from"mint"and0edits from"min", whereas"pint"and"mist"are2edits away."planets"has length7, which is more than1character longer than any word indictionary, so[]is returned immediately.
Constraints
0 <= len(dictionary) <= 50,000- Every entry in
dictionaryis unique, with0 <= len(word) <= 20. len(operations) == len(arguments), and each"search"call supplies[query]with0 <= len(query).- Index initialization must finish comfortably within a few seconds, and each
searchcall must avoid scanning the full dictionary.
Step-by-step walkthrough
Restate the problem
We are given a fixed vocabulary of up to
N = 50,000unique words, each of length at mostL = 20, followed by repeatedsearch(query)calls. Eachsearch(query)must return all words indictionarywhose Levenshtein distance — the minimum number of single-character insertions, deletions, or substitutions needed to convertqueryintoword— is0or1, preserving their original order indictionary. (Note that swapping two adjacent letters, such as"stnoe"vs."stone", takes2Levenshtein substitutions and is not a match.)The judge invokes
fuzzy_keyword_index(dictionary, operations, arguments), which initializes oneFuzzyIndex(dictionary)upfront and runs each"search"operation in sequence.Fast exact check for distance 0 or 1
Before building any index, how do we verify whether two strings
aandbsit within1edit? Instead of anO(len(a) × len(b))dynamic-programming grid, one linear scan suffices:- If
abs(len(a) - len(b)) > 1, a single insertion or deletion cannot equalize their lengths, so returnFalse. - Order the pair so
len(a) <= len(b)(meaningbhas either the same length asaor1extra character), and advance indexipast their matching prefix. - If
i == len(a), all ofamatchedb, andbhas at most1trailing character ->True. - Otherwise
imarks the first mismatch:- Equal lengths (
len(a) == len(b)): our lone edit must substitutea[i]withb[i], so the remaining tailsa[i + 1:]andb[i + 1:]must match. - Unequal lengths (
len(b) == len(a) + 1): our lone edit must deleteb[i]fromb, soa[i:]must equalb[i + 1:].
- Equal lengths (
def within_one_edit(a: str, b: str) -> bool: """Return True if Levenshtein distance between a and b is 0 or 1.""" # A single insertion or deletion changes length by at most 1. if abs(len(a) - len(b)) > 1: return False # Order the pair so len(a) <= len(b), meaning len(b) - len(a) is 0 or 1. if len(a) > len(b): a, b = b, a # Advance past the matching prefix. i = 0 while i < len(a) and a[i] == b[i]: i += 1 # All of a matched: b has either 0 extra characters (exact match) or 1 at the end. if i == len(a): return True # First mismatch is at index i: # - Equal lengths: only 1 substitution at i can fix it, so suffixes after i must match. if len(a) == len(b): return a[i + 1:] == b[i + 1:] # - len(b) == len(a) + 1: only deleting b[i] can fix it, so a[i:] must equal b[i + 1:]. return a[i:] == b[i + 1:]Running
within_one_editacross allN = 50,000words on every query would still costO(N · L)time per search — up to a million character checks per call. We need an index that narrows50,000words down to a tiny set of candidates, and then we runwithin_one_editonly on those candidates.- If
Key idea: meet in the middle using only deletions
Why not precompute every distance-1 neighbor of every dictionary word? Over
26lowercase letters, a20-character word has20deletions,20 × 25 = 500substitutions, and21 × 26 = 546single-character insertions — over1,050strings per word, or more than50 millionhash entries across50,000words.We shrink that
50×by applying deletions to both sides. Definedeletion_keys(s)assitself (0deletions) plus every string produced by deleting1character froms(at mostL + 1 = 21strings). Wheneverqueryandwordsit at edit distance0or1,deletion_keys(query)anddeletion_keys(word)are guaranteed to share at least one key:Edit relationship query word Shared key in both deletion_keys(...) ------------------------ --------- -------- ------------------------------------- 0 edits (identical) "store" "store" "store" (0 deletions from each) 1 insertion into query "ston" "stone" "ston" (0 from query, delete 'e' from word) 1 deletion from query "mint" "min" "min" (delete 't' from query, 0 from word) 1 substitution at index "store" "stone" "stoe" (delete index 3 from BOTH strings)Keep in mind that sharing a deletion key is necessary, not sufficient! For instance,
"stnoe"and"stone"both delete'n'to produce"stoe", yet transforming"stnoe"into"stone"takes2edits. That is why every bucket hit is verified withwithin_one_edit.Build the deletion-key index
For each word at position
indexindictionary, we gatherdeletion_keys(word)as aset(so repeated letters like"aaa"->"aa"never appendindexto the same bucket twice) and appendindextoself.buckets[key]. Storing integer indices lets us sort candidate indices at search time to preservedictionaryorder, whileself.max_lenlets us reject overly long queries inO(1)time.def deletion_keys(word: str) -> Set[str]: """Return the word itself (0 deletions) plus all strings with 1 character deleted.""" # Using a set deduplicates keys when repeated letters produce the same slice # (for example, deleting any character of "aaa" gives "aa"). keys = {word} for i in range(len(word)): keys.add(word[:i] + word[i + 1:]) return keys class FuzzyIndex: def __init__(self, dictionary: List[str]): # words: copy of input dictionary preserving original index order. self.words: List[str] = list(dictionary) self.max_len: int = 0 # buckets: maps deletion_key (str) -> word indices (List[int]), e.g. {"stoe": [0, 1]}. self.buckets: Dict[str, List[int]] = {} for index, word in enumerate(self.words): if len(word) > self.max_len: self.max_len = len(word) for key in deletion_keys(word): if key not in self.buckets: self.buckets[key] = [] self.buckets[key].append(index)Search by looking up query keys and verifying candidates
To execute
search(query): 1. Iflen(query) > self.max_len + 1, return[]immediately without allocating substrings. 2. Union the bucket lists for allkey in deletion_keys(query)intocandidate_indices(set) so each candidate word is checked at most once even when multiple keys collide. 3. Walksorted(candidate_indices)and keep words wherewithin_one_edit(query, word)returnsTrue.Why does the candidate set stay tiny even when
N = 50,000? Because dictionary words are unique, any single keykcan only originate fromkitself or from inserting one character intok(at most1 + (len(k) + 1) × σwords over an alphabet of sizeσ).def search(self, query: str) -> List[str]: # Even deleting 1 character leaves len(query) - 1 > self.max_len, so nothing can match. if len(query) > self.max_len + 1: return [] # Phase 1: Collect candidate word indices that share at least one 0/1-deletion key. candidate_indices: Set[int] = set() for key in deletion_keys(query): for index in self.buckets.get(key, []): candidate_indices.add(index) # Phase 2: Verify candidates in dictionary order. Sharing a deletion key is necessary # but not sufficient ("ab" and "ba" both delete 'b' to "a" yet are 2 edits apart). matches: List[str] = [] for index in sorted(candidate_indices): word = self.words[index] if within_one_edit(query, word): matches.append(word) return matchesTrace through Example 1
With
dictionary = ["stone", "store", "tone", "storm", "plum"](indices0..4): -"stone"(0) indexes{"stone", "tone", "sone", "stne", "stoe", "ston"}-"store"(1) indexes{"store", "tore", "sore", "stre", "stoe", "stor"}-"tone"(2) indexes{"tone", "one", "tne", "toe", "ton"}-"storm"(3) indexes{"storm", "torm", "sorm", "strm", "stom", "stor"}-"plum"(4) indexes{"plum", "lum", "pum", "plm", "plu"}Query Query deletion keys Bucket hits Exact check (within_one_edit) --------------- ------------------------------------------ ----------------- --------------------------------------------- search("store") {store, tore, sore, stre, stoe, stor} "stoe"->[0, 1] 0 "stone": 1 substitution at i=3 -> True "store"->[1], ... 1 "store": 0 edits -> True "stor"->[1, 3] 3 "storm": 1 substitution at i=4 -> True cands: {0, 1, 3} returns ['stone', 'store', 'storm'] search("ston") {ston, ton, son, stn, sto} "ston"->[0] 0 "stone": 1 extra char 'e' at end -> True "ton"->[2] 2 "tone": mismatch at i=0, "ton"!="one" -> False cands: {0, 2} returns ['stone'] search("stnoe") {stnoe, tnoe, snoe, stoe, stne, stno} "stoe"->[0, 1] 0 "stone": mismatch at i=2, "oe"!="ne" -> False "stne"->[0] 1 "store": mismatch at i=2, "oe"!="re" -> False cands: {0, 1} returns []Complete solution
Wrap
FuzzyIndexinsidefuzzy_keyword_indexto run all operations for the judge.from typing import Any, Dict, List, Optional, Set, Tuple def deletion_keys(word: str) -> Set[str]: """Return the word itself (0 deletions) plus all strings with 1 character deleted.""" # Using a set deduplicates keys when repeated letters produce the same slice # (for example, deleting any character of "aaa" gives "aa"). keys = {word} for i in range(len(word)): keys.add(word[:i] + word[i + 1:]) return keys def within_one_edit(a: str, b: str) -> bool: """Return True if Levenshtein distance between a and b is 0 or 1.""" # A single insertion or deletion changes length by at most 1. if abs(len(a) - len(b)) > 1: return False # Order the pair so len(a) <= len(b), meaning len(b) - len(a) is 0 or 1. if len(a) > len(b): a, b = b, a # Advance past the matching prefix. i = 0 while i < len(a) and a[i] == b[i]: i += 1 # All of a matched: b has either 0 extra characters (exact match) or 1 at the end. if i == len(a): return True # First mismatch is at index i: # - Equal lengths: only 1 substitution at i can fix it, so suffixes after i must match. if len(a) == len(b): return a[i + 1:] == b[i + 1:] # - len(b) == len(a) + 1: only deleting b[i] can fix it, so a[i:] must equal b[i + 1:]. return a[i:] == b[i + 1:] class FuzzyIndex: def __init__(self, dictionary: List[str]): # words: copy of input dictionary preserving original index order. self.words: List[str] = list(dictionary) self.max_len: int = 0 # buckets: maps deletion_key (str) -> word indices (List[int]), e.g. {"stoe": [0, 1]}. self.buckets: Dict[str, List[int]] = {} for index, word in enumerate(self.words): if len(word) > self.max_len: self.max_len = len(word) for key in deletion_keys(word): if key not in self.buckets: self.buckets[key] = [] self.buckets[key].append(index) def search(self, query: str) -> List[str]: # Even deleting 1 character leaves len(query) - 1 > self.max_len, so nothing can match. if len(query) > self.max_len + 1: return [] # Phase 1: Collect candidate word indices that share at least one 0/1-deletion key. candidate_indices: Set[int] = set() for key in deletion_keys(query): for index in self.buckets.get(key, []): candidate_indices.add(index) # Phase 2: Verify candidates in dictionary order. Sharing a deletion key is necessary # but not sufficient ("ab" and "ba" both delete 'b' to "a" yet are 2 edits apart). matches: List[str] = [] for index in sorted(candidate_indices): word = self.words[index] if within_one_edit(query, word): matches.append(word) return matches def fuzzy_keyword_index( dictionary: List[str], operations: List[str], arguments: List[List[str]], ) -> List[Optional[List[str]]]: index = FuzzyIndex(dictionary) results: List[Optional[List[str]]] = [] for op, args in zip(operations, arguments): if op == "search": results.append(index.search(args[0])) else: raise ValueError(f"unknown operation: {op}") return results✅ Submit now — all tests should pass.
Intuition & how it works
Think of matching a slightly misspelled query to a dictionary word as meeting halfway at a shared "skeleton". Levenshtein distance (also called edit distance) is the minimum number of single-character insertions, deletions, or substitutions needed to turn one string into another. Instead of guessing which of the 26 letters might be inserted or substituted at every position, notice a clean symmetry: if query and word are at most 1 edit apart, erasing 0 or 1 character from query and erasing 0 or 1 character from word is guaranteed to produce at least one identical string. Indexing every word under its 0- and 1-deletion skeletons (a symmetric deletion index, popularized by SymSpell) lets queries jump straight to candidate words with a few hash-map lookups, followed by a fast exact check.
Comparing query directly against all 50,000 words on every search would perform up to a million character checks per call. Conversely, pre-generating every 1-edit insertion, deletion, and substitution for every dictionary word bloats memory: a 20-letter word has roughly 1,050 single-edit neighbors, creating more than 50 million hash-table keys across 50,000 words instead of at most 21 deletion keys per word.
Trace a slice of Example 1 with dictionary = ["stone", "store", "tone"] (indices 0, 1, 2):
1. Index build: "stone" (0) goes into {"stone", "tone", "sone", "stne", "stoe", "ston"}; "store" (1) goes into {"store", "tore", "sore", "stre", "stoe", "stor"}; "tone" (2) goes into {"tone", "one", "tne", "toe", "ton"}.
2. Search "store": Its deletion keys include "stoe" (hitting [0, 1]) and "store" (hitting [1]). Sorting {0, 1} and checking within_one_edit confirms both "stone" (1 substitution) and "store" (0 edits), returning ["stone", "store"].
3. Why exact verification matters: When searching "stnoe", deleting 'n' also hits "stoe" ([0, 1]), and within_one_edit("stnoe", "stone") catches that swapping 'n' and 'o' actually costs 2 edits, returning [].
Complexity
Let N be the number of dictionary words (≤ 50,000), L the maximum word length (≤ 20), σ the alphabet size, and m the query length.
- Preprocessing time:
O(N · L²). Each of theNwords produces at mostL + 1deletion keys, and slicing/hashing each key copies up toLcharacters. For50,000words of length≤ 20, that is at most1.05 millionshort strings and builds in well under a second in Python. - Index space:
O(N · L)bucket references (O(N · L²)total characters across distinct key strings). Each word index is stored in at mostL + 1buckets. - Search time:
O(m² + C · (m + log C))whenm ≤ L + 1, andO(1)whenm > L + 1(due to themax_len + 1length guard). Generating them + 1query keys takesO(m²), sorting theCcandidate indices takesO(C log C), and runningwithin_one_editon each candidate takesO(C · m). Crucially,Cdoes not grow withN: because dictionary words are unique, any single key of lengthkcan come from at most1 + (k + 1) · σwords (kitself plus single-letter insertions intok), soC ≤ (m + 1) · (1 + (m + 1) · σ)and is typically just a few words in practice.
Edge cases
- Empty dictionary (
[]):self.max_lenstays0,self.bucketsis empty, and every search returns[]. - Empty query (
""):deletion_keys("")is{""}, which hits""(0 deletions) and every 1-character word in the dictionary (1 deletion) — the exact set of strings within1edit of"". - Very long queries (
len(query) >= max_len + 2, such as"planets"in Example 2): Rejected inO(1)time before slicing any substrings, so a100,000-character query cannot slow the service down. - Very short queries against long words: Query keys have length
morm - 1, whereas a wordwonly produces keys of lengthlen(w)orlen(w) - 1; words differing in length by2+never share a key and never reachwithin_one_edit. - Repeated characters (
"aaa"): Deleting index0,1, or2all yield"aa"; becausedeletion_keysreturns asetandcandidate_indicesis aset, each word is indexed and returned at most once. - Transpositions (
"stnoe"vs."stone","ab"vs."ba"): Standard Levenshtein distance counts an adjacent swap as2substitutions (or1deletion +1insertion =2edits), sowithin_one_editproperly rejects them even though they share deletion keys.
Common mistakes
- Skipping
within_one_editand returning every bucket hit:"ab"and"ba"both delete'b'to"a", and"stnoe"and"stone"both delete to"stoe"and"stne", yet both pairs have Levenshtein distance2. - Forgetting to include the unedited string (
0deletions) indeletion_keys: Withoutwordindeletion_keys(word), a query with1extra character ("mints"vs."mint") will miss; withoutqueryindeletion_keys(query), a query missing1character ("ston"vs."stone") will miss. - Deleting characters only from dictionary words (not from the query): That catches missing letters in the query (
"ston"matches"stone"), but misses substitutions ("store"vs."stone"only meet at"stoe"when both sides delete index3) and extra letters in the query ("stones"vs."stone"). - Adding duplicate bucket entries for repeated letters: Appending to buckets in a raw loop without deduplicating
deletion_keys(word)causes"aaa"to appear three times under"aa". - Confusing Levenshtein distance with Damerau-Levenshtein distance: Damerau-Levenshtein distance adds a fourth operation — swapping two adjacent characters for cost
1— whereas standard Levenshtein distance allows only insert, delete, and substitute.
Alternative approaches
- Query-side 1-edit expansion against a hash set: Store
dictionaryin a plainset(O(N · L)memory) and, at query time, generate all1 + σ · (2m + 1)strings within1edit ofquery(mdeletions,m · (σ - 1)substitutions,(m + 1) · σinsertions) and check set membership. This uses minimal index memory and zero preprocessing beyond building the set, at the cost of ~1,050hash lookups per20-letter lowercase query (and gets slow if the character set is full Unicode rather thana–z). - Trie with dynamic-programming row pruning: A trie (prefix tree) stores words in a tree where common prefixes share nodes. During
search(query), traverse the trie depth-first while maintaining one row of the Levenshtein dynamic-programming table at each node, and prune an entire subtree whenever every entry in that row exceeds1. This generalizes cleanly to largerK, though in Python per-node object overhead makes a dict-per-node trie roughly comparable in memory to the deletion index while visiting hundreds of nodes per query. - BK-tree: A BK-tree (Burkhard-Keller tree) organizes words into a tree where edges are labeled by exact edit distance and uses the triangle inequality (
|d(q, w) - d(q, root)| ≤ K) to skip subtrees. It handles arbitraryK, but visits noticeably more nodes than hash-based deletion lookup forK = 1.
Follow-up questions
- How would your design change if queries allowed an edit distance of up to 2 instead of 1? The symmetric deletion property still holds at threshold
2: any two strings within2edits must share a skeleton obtained by deleting0,1, or2characters from each side. A20-character word yields at most1 + L + L · (L - 1) / 2 = 1 + 20 + 190 = 211deletion keys (~10.5 millionbucket entries across50,000words), and each candidate is checked with a banded Levenshtein routine that evaluates only cells|i - j| <= 2inO(K · L)time. Because211keys per word uses roughly10×the memory of distance1, when memory is constrained we can switch to a trie search that prunes branches whenevermin(dp_row) > 2, keeping index memory independent of the edit threshold. - How does the memory footprint of precomputing all one-edit neighbors compare against traversing a prefix tree (trie) at query time? Pre-generating every single-edit insertion, deletion, and substitution gives
O(m)single-lookup queries, yet stores up to1 + σ · (2L + 1) ≈ 1,067keys per20-letter lowercase word — up to~53 millionstrings (several gigabytes in Python) across50,000words, and completely impractical over full Unicode. A trie shares common prefixes across words (at mostN · L ≤ 1,000,000nodes regardless of alphabet size or threshold), trading smaller theoretical space for slower queries that update DP rows across hundreds of prefix nodes. Symmetric deletion sits in the sweet spot for distance1: it is alphabet-independent, stores at mostL + 1 = 21keys per word (~50×smaller than full neighbor expansion), and still resolves queries in a handful of hash lookups. - How could you support live insertions and deletions of dictionary words without rebuilding the entire index? Assign each inserted word a monotonically increasing integer
word_id, maintainid_to_word: Dict[int, str]andword_to_id: Dict[str, int], and store asetofword_ids in eachself.buckets[key]rather than alist. Adding a word inserts itsword_idinto its≤ L + 1bucket sets inO(L²)time, and removing a word deletes itsword_idfrom those same≤ L + 1bucket sets (dropping empty keys) inO(L²)time while sorting candidateword_ids preserves insertion order. Under heavy concurrent traffic, production search engines pair a read-only main index with a small mutable delta index plus a tombstone set of deleted IDs, periodically compacting them in the background so readers never contend on locks.
Follow-up questions
- How would your design change if queries allowed an edit distance of up to 2 instead of 1?
- How does the memory footprint of precomputing all one-edit neighbors compare against traversing a prefix tree (trie) at query time?
- How could you support live insertions and deletions of dictionary words without rebuilding the entire index?
Similar questions
- Enterprise Hybrid Document Ingestion and Semantic Search
- Core Priorities and Role Alignment for Software Engineers
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance