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 in dictionary once upfront.
  • FuzzyIndex.search(self, query: str) -> List[str]: Returns every matching word from dictionary within edit distance 1 of query, preserving their original order in dictionary.
  • fuzzy_keyword_index(dictionary, operations, arguments): Instantiates FuzzyIndex(dictionary) and executes each operation in operations with the matching argument list in arguments (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" (1 substitution: 'r' -> 'n'), "store" (0 edits), and "storm" (1 substitution: 'e' -> 'm'), returned in dictionary order ("stone" appears before "store"). "tone" needs 2 edits (delete 's' and 'r' -> 'n').
    • Searching "ston" matches "stone" via 1 insertion ('e').
    • Searching "stnoe" differs from "stone" at two positions ('n' and 'o' swapped), which takes 2 Levenshtein edits and returns [].

Example 2

  • Input:
    • dictionary = ["mint", "min", "pint", "mist"]
    • operations = ["search", "search"]
    • arguments = [["min"], ["planets"]]
  • Output: [["mint", "min"], []]
  • Explanation: "min" is 1 insertion away from "mint" and 0 edits from "min", whereas "pint" and "mist" are 2 edits away. "planets" has length 7, which is more than 1 character longer than any word in dictionary, so [] is returned immediately.

Constraints

  • 0 <= len(dictionary) <= 50,000
  • Every entry in dictionary is unique, with 0 <= len(word) <= 20.
  • len(operations) == len(arguments), and each "search" call supplies [query] with 0 <= len(query).
  • Index initialization must finish comfortably within a few seconds, and each search call must avoid scanning the full dictionary.

Step-by-step walkthrough

  1. Restate the problem

    We are given a fixed vocabulary of up to N = 50,000 unique words, each of length at most L = 20, followed by repeated search(query) calls. Each search(query) must return all words in dictionary whose Levenshtein distance — the minimum number of single-character insertions, deletions, or substitutions needed to convert query into word — is 0 or 1, preserving their original order in dictionary. (Note that swapping two adjacent letters, such as "stnoe" vs. "stone", takes 2 Levenshtein substitutions and is not a match.)

    The judge invokes fuzzy_keyword_index(dictionary, operations, arguments), which initializes one FuzzyIndex(dictionary) upfront and runs each "search" operation in sequence.

  2. Fast exact check for distance 0 or 1

    Before building any index, how do we verify whether two strings a and b sit within 1 edit? Instead of an O(len(a) × len(b)) dynamic-programming grid, one linear scan suffices:

    1. If abs(len(a) - len(b)) > 1, a single insertion or deletion cannot equalize their lengths, so return False.
    2. Order the pair so len(a) <= len(b) (meaning b has either the same length as a or 1 extra character), and advance index i past their matching prefix.
    3. If i == len(a), all of a matched b, and b has at most 1 trailing character -> True.
    4. Otherwise i marks the first mismatch:
      • Equal lengths (len(a) == len(b)): our lone edit must substitute a[i] with b[i], so the remaining tails a[i + 1:] and b[i + 1:] must match.
      • Unequal lengths (len(b) == len(a) + 1): our lone edit must delete b[i] from b, so a[i:] must equal b[i + 1:].
    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_edit across all N = 50,000 words on every query would still cost O(N · L) time per search — up to a million character checks per call. We need an index that narrows 50,000 words down to a tiny set of candidates, and then we run within_one_edit only on those candidates.

  3. Key idea: meet in the middle using only deletions

    Why not precompute every distance-1 neighbor of every dictionary word? Over 26 lowercase letters, a 20-character word has 20 deletions, 20 × 25 = 500 substitutions, and 21 × 26 = 546 single-character insertions — over 1,050 strings per word, or more than 50 million hash entries across 50,000 words.

    We shrink that 50× by applying deletions to both sides. Define deletion_keys(s) as s itself (0 deletions) plus every string produced by deleting 1 character from s (at most L + 1 = 21 strings). Whenever query and word sit at edit distance 0 or 1, deletion_keys(query) and deletion_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" takes 2 edits. That is why every bucket hit is verified with within_one_edit.

  4. Build the deletion-key index

    For each word at position index in dictionary, we gather deletion_keys(word) as a set (so repeated letters like "aaa" -> "aa" never append index to the same bucket twice) and append index to self.buckets[key]. Storing integer indices lets us sort candidate indices at search time to preserve dictionary order, while self.max_len lets us reject overly long queries in O(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)
    
  5. Search by looking up query keys and verifying candidates

    To execute search(query): 1. If len(query) > self.max_len + 1, return [] immediately without allocating substrings. 2. Union the bucket lists for all key in deletion_keys(query) into candidate_indices (set) so each candidate word is checked at most once even when multiple keys collide. 3. Walk sorted(candidate_indices) and keep words where within_one_edit(query, word) returns True.

    Why does the candidate set stay tiny even when N = 50,000? Because dictionary words are unique, any single key k can only originate from k itself or from inserting one character into k (at most 1 + (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 matches
    
  6. Trace through Example 1

    With dictionary = ["stone", "store", "tone", "storm", "plum"] (indices 0..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 []
    
  7. Complete solution

    Wrap FuzzyIndex inside fuzzy_keyword_index to 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 the N words produces at most L + 1 deletion keys, and slicing/hashing each key copies up to L characters. For 50,000 words of length ≤ 20, that is at most 1.05 million short 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 most L + 1 buckets.
  • Search time: O(m² + C · (m + log C)) when m ≤ L + 1, and O(1) when m > L + 1 (due to the max_len + 1 length guard). Generating the m + 1 query keys takes O(m²), sorting the C candidate indices takes O(C log C), and running within_one_edit on each candidate takes O(C · m). Crucially, C does not grow with N: because dictionary words are unique, any single key of length k can come from at most 1 + (k + 1) · σ words (k itself plus single-letter insertions into k), so C ≤ (m + 1) · (1 + (m + 1) · σ) and is typically just a few words in practice.

Edge cases

  • Empty dictionary ([]): self.max_len stays 0, self.buckets is 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 within 1 edit of "".
  • Very long queries (len(query) >= max_len + 2, such as "planets" in Example 2): Rejected in O(1) time before slicing any substrings, so a 100,000-character query cannot slow the service down.
  • Very short queries against long words: Query keys have length m or m - 1, whereas a word w only produces keys of length len(w) or len(w) - 1; words differing in length by 2+ never share a key and never reach within_one_edit.
  • Repeated characters ("aaa"): Deleting index 0, 1, or 2 all yield "aa"; because deletion_keys returns a set and candidate_indices is a set, each word is indexed and returned at most once.
  • Transpositions ("stnoe" vs. "stone", "ab" vs. "ba"): Standard Levenshtein distance counts an adjacent swap as 2 substitutions (or 1 deletion + 1 insertion = 2 edits), so within_one_edit properly rejects them even though they share deletion keys.

Common mistakes

  • Skipping within_one_edit and 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 distance 2.
  • Forgetting to include the unedited string (0 deletions) in deletion_keys: Without word in deletion_keys(word), a query with 1 extra character ("mints" vs. "mint") will miss; without query in deletion_keys(query), a query missing 1 character ("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 index 3) 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 dictionary in a plain set (O(N · L) memory) and, at query time, generate all 1 + σ · (2m + 1) strings within 1 edit of query (m deletions, 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,050 hash lookups per 20-letter lowercase query (and gets slow if the character set is full Unicode rather than a–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 exceeds 1. This generalizes cleanly to larger K, 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 arbitrary K, but visits noticeably more nodes than hash-based deletion lookup for K = 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 within 2 edits must share a skeleton obtained by deleting 0, 1, or 2 characters from each side. A 20-character word yields at most 1 + L + L · (L - 1) / 2 = 1 + 20 + 190 = 211 deletion keys (~10.5 million bucket entries across 50,000 words), and each candidate is checked with a banded Levenshtein routine that evaluates only cells |i - j| <= 2 in O(K · L) time. Because 211 keys per word uses roughly 10× the memory of distance 1, when memory is constrained we can switch to a trie search that prunes branches whenever min(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 to 1 + σ · (2L + 1) ≈ 1,067 keys per 20-letter lowercase word — up to ~53 million strings (several gigabytes in Python) across 50,000 words, and completely impractical over full Unicode. A trie shares common prefixes across words (at most N · L ≤ 1,000,000 nodes 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 distance 1: it is alphabet-independent, stores at most L + 1 = 21 keys 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, maintain id_to_word: Dict[int, str] and word_to_id: Dict[str, int], and store a set of word_ids in each self.buckets[key] rather than a list. Adding a word inserts its word_id into its ≤ L + 1 bucket sets in O(L²) time, and removing a word deletes its word_id from those same ≤ L + 1 bucket sets (dropping empty keys) in O(L²) time while sorting candidate word_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

Similar questions

More Workday interview questions

All 3 Workday questions →