Type "teh" into a search box and it still finds "the." Mistype "pyton" and the IDE still suggests "python." Behind these everyday miracles sits a single idea: edit distance.
The Levenshtein distance between two strings is the minimum number of single-character insertions, deletions, and substitutions needed to transform one into the other. "kitten" → "sitting" takes three such operations (substitute k→s, substitute e→i, insert g), so their edit distance is 3. Two identical strings have distance 0; every character difference adds at least 1.
Computing that distance for a single pair is solved — Vladimir Levenshtein worked out the dynamic-programming recurrence in 1965 — and the result runs in time where and are the string lengths. That is cheap enough to run thousands of times per keystroke on the dictionary of a typical autocomplete engine.
The real engineering question is: given a user's (possibly misspelled) prefix, how do you efficiently find all dictionary words within edit distance without comparing the query to every entry? The answer is to walk a trie — a prefix tree — while carrying the DP matrix forward one column at a time, pruning branches the moment their distance already exceeds . This turns a brute-force scan into something that feels instant.
Comments
Loading comments...