Typo-Tolerant Word Lookup with One Edit
Data Structure DesignAuto-graded · 17 test casesLast updated
Answer batches of lookups against a fixed word list, returning every word within Levenshtein distance 1 of the query, using a deletion-based hash index.
Typo-Tolerant Word Lookup
A spell-suggestion feature works against a fixed list of words. A word is a suggestion for a query if the two strings are at most one edit apart. Because many queries hit the same list, each lookup should be much faster than comparing the query to every word.
The service is driven by a sequence of operations, which you process in one function call.
Edit distance
Use the standard Levenshtein distance. One edit is one of:
- inserting a single character,
- deleting a single character,
- replacing a single character with another one.
Swapping two adjacent characters is not a single edit. For example, "appel" and "apple" are at distance 2.
A word matches a query if its distance to the query is 0 or 1.
Task
Implement a function that receives:
words: the list of dictionary words. It may contain duplicates, which should be treated as a single word.operations: a list of operation names.arguments: a list of the same length asoperations.arguments[i]is the list of arguments foroperations[i].
Process the operations in order. The dictionary is fixed for the whole call. Each operation contributes one entry to the returned list:
"init": nothing needs to be done. OutputNonefor it."search":arguments[i][0]is the query string. Output a list of all distinct dictionary words whose edit distance to the query is 0 or 1, sorted in ascending lexicographic order. Output[]if there are none.
Any other operation name should raise a ValueError.
Constraints
- The number of distinct words is at most 50,000.
- Each word has length at most 20.
- Queries may be empty, and may be much longer or shorter than every dictionary word.
- The dictionary may be empty.
- Words and queries are strings. Comparison is case-sensitive and exact.
- Lookups should be considerably faster than a scan over the whole dictionary.
Examples
Example 1
Input: fuzzy_lookup_batch(['apple', 'apply', 'banana', 'pear'], ['search', 'search', 'search'], [['appel'], ['apple'], ['banan']])
Output: [[], ['apple', 'apply'], ['banana']]
Hints
Hint 1
Two strings within one edit share a common string if you allow deleting at most one character from each of them. Which edit types does this cover: insertion, deletion, substitution?
Hint 2
Precompute a hash map from every 'word with at most one character removed' (including the word itself) to the dictionary words that produce it. A query then only needs about L+1 map lookups.
Hint 3
Sharing a key is necessary but not sufficient: 'ab' and 'ba' both reduce to 'a' but are at distance 2. Verify each candidate with a linear scan that tolerates at most one mismatch, and deduplicate and sort the results.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Build a deletion index. For every distinct dictionary word w, store w itself and every string obtained by deleting exactly one character from w as keys in a hash map. Each key maps to the set of words that produce it.
To answer a query q, generate q and all of its single-character deletions, look each up in the map, and union the buckets. This gives a small candidate set. Then check each candidate with an exact linear-time "within one edit" test, and return the survivors sorted.
Why it is correct
Two strings q and w at distance at most 1 always share a key:
- Equal:
qandware the same key. wisqplus one inserted character: deleting that character fromwgivesq.wisqminus one character: deleting that character fromqgivesw.- Substitution at position
i: deleting positionifrom both gives the same string.
So every true match is among the candidates (no misses). Sharing a key is not enough, though. For instance, "ab" and "ba" share the key "a" but are at distance 2. The verification step within_one checks the real definition: it walks both strings, allows one mismatch, and on a mismatch advances both pointers when the lengths are equal (substitution) or only the longer string's pointer when they differ (insertion or deletion). An unmatched leftover character counts as an edit. This removes false positives.
Using a set of candidates avoids duplicates, and sorting gives deterministic output. Duplicate dictionary words collapse because the dictionary is turned into a set. An empty query generates only the key "", which matches the empty word and all one-letter words. An empty dictionary yields an empty map, so every search returns [].
Complexity
Let N be the number of distinct words and L the maximum length.
- Preprocessing: O(N · L²) time, since each word creates L+1 keys that each cost O(L) to build. Space is O(N · L) keys.
- Each search: O(L²) to build and hash the query keys, plus O(C · L) to verify C candidates. C is normally small, so this is far cheaper than the O(N · L) scan.
Reference solution
from collections import defaultdict
from typing import List, Optional
def fuzzy_lookup_batch(words: List[str], operations: List[str], arguments: List[List[str]]) -> List[Optional[List[str]]]:
unique_words = set(words)
buckets = defaultdict(set)
for word in unique_words:
buckets[word].add(word)
for i in range(len(word)):
buckets[word[:i] + word[i + 1:]].add(word)
def within_one(a, b):
if abs(len(a) - len(b)) > 1:
return False
if len(a) > len(b):
a, b = b, a
i = j = edits = 0
while i < len(a) and j < len(b):
if a[i] == b[j]:
i += 1
j += 1
else:
edits += 1
if edits > 1:
return False
if len(a) == len(b):
i += 1
j += 1
if i < len(a) or j < len(b):
edits += 1
return edits <= 1
output = []
for op, args in zip(operations, arguments):
if op == "init":
output.append(None)
elif op == "search":
query = args[0]
candidates = set(buckets.get(query, ()))
for i in range(len(query)):
candidates.update(buckets.get(query[:i] + query[i + 1:], ()))
output.append(sorted(w for w in candidates if within_one(query, w)))
else:
raise ValueError(f"Unknown operation: {op}")
return output