Forward Deployed EngineeringCoding and AlgorithmsDynamic Programming
Compute the edit distance (Levenshtein) between two strings.
Question 6 of 9 · Updated
On this page
Interview-ready answer#
I would use dynamic programming to compute the minimum number of single-character insertions, deletions, and substitutions needed to turn one string into the other. Assuming each operation costs one, I define dp[i][j] as the edit distance between the first i characters of the source and the first j characters of the target. If the last characters match, I carry forward the diagonal value; otherwise I take one plus the minimum of deleting, inserting, or substituting. The full table takes O(mn) time and O(mn) space. Since each cell depends only on the current and previous rows, I can reduce auxiliary space to O(min(m,n)) if the interviewer only needs the distance, not the edit sequence.
Deriving the recurrence#
Let m = len(a) and n = len(b). Initialize dp[i][0] = i (delete all characters) and dp[0][j] = j (insert all characters). For nonempty prefixes:
dp[i][j] = min(
dp[i-1][j] + 1,
dp[i][j-1] + 1,
dp[i-1][j-1] + (a[i-1] != b[j-1])
)The three terms correspond to deletion, insertion, and substitution or match, respectively. This works because an optimal alignment of two prefixes ends in one of those three cases; the remaining prefixes must also be optimally aligned. The table evaluates every relevant smaller subproblem exactly once.
Worked example#
Transform kitten into sitting: kitten → sitten (substitute k with s), sitten → sittin (substitute e with i), sittin → sitting (insert g). The dynamic programming result is 3. Merely counting mismatched positions cannot handle insertions and deletions correctly.
Python implementation (space optimized)#
PYTHONdef edit_distance(a: str, b: str) -> int: # Keep the shorter string along the columns. if len(a) < len(b): a, b = b, a previous = list(range(len(b) + 1)) for i, char_a in enumerate(a, 1): current = [i] + [0] * len(b) for j, char_b in enumerate(b, 1): current[j] = min( previous[j] + 1, # Deletion current[j - 1] + 1, # Insertion previous[j - 1] + (char_a != char_b) ) previous = current return previous[-1] print(edit_distance('kitten', 'sitting')) # 3 print(edit_distance('', 'abc')) # 3 print(edit_distance('same', 'same')) # 0
Swapping the inputs is safe because standard unit-cost Levenshtein distance is symmetric. In the inner loop, the previous row supplies the deletion and diagonal costs, while the current row supplies the insertion cost. The final cell is the minimum cost for the complete strings.
Local verification: 967 checks passed: all 961 ordered pairs of binary strings of length zero through four compared with an independently implemented full-table DP, plus six explicit edge and example cases. This validates the tested implementation, not all possible inputs.
Complexity and trade-offs#
- Time: O(mn) for nonempty inputs; the loops and initialization also account for empty inputs.
- Auxiliary space: O(min(m,n) + 1), conventionally written O(min(m,n)).
- If an actual edit sequence is required, retain the full DP table and backtrack through the chosen operations (or use a more advanced linear-space reconstruction algorithm).
- If only distances up to a threshold k matter, first reject pairs whose length difference exceeds k. A banded DP can restrict computation to cells within k of the diagonal and return an above-threshold result when no valid alignment remains. This is useful when k is much smaller than string lengths.
How an FDE applies this in production#
Imagine integrating two customer systems whose supplier names differ because of typos or inconsistent data entry. I would use exact identifier matches first, normalize text using business-approved rules, narrow candidates using indexed blocking or retrieval, and then score shortlisted names using edit distance. For comparisons across different lengths, a possible similarity score is 1 - distance / max(m, n) (define similarity as 1 for two empty strings). This is a heuristic score, not a calibrated probability.
I would validate thresholds on labeled customer records, measure precision and recall, and send ambiguous matches to human review rather than automatically merging records. For multilingual data, define Unicode normalization and whether to compare code points or grapheme clusters. For millions of records, avoid all-pairs comparison and monitor candidate recall, latency, and false merges. Edit distance captures spelling similarity, not semantic equivalence; names with different spellings but identical meaning may need other matching signals.
Likely interviewer follow-ups#
- How do you return the actual edit operations? Backtrack through a full DP table; each move identifies a match, insertion, deletion, or substitution.
- How is Damerau–Levenshtein different? It also permits adjacent transpositions as an edit; ordinary Levenshtein does not.
- What if edits have different costs? Replace unit costs with the specified nonnegative costs, and revisit symmetry before swapping inputs.
- How would you make matching scale? Use candidate generation, length filters, bounded distance, and threshold tuning based on labeled examples.
References
- 1.
- 2.
- 3.FDE Interviews — source questionfdeinterviews.com
Related questions
Explore other topics:AI AgentsAI System DesignLarge Language Models