Edit Distance for OCR Correction
Problem Statement
In Optical Character Recognition (OCR), text extracted from images often contains errors. Edit Distance (Levenshtein Distance) measures how different two strings are, which helps in:
- Spell checking OCR output
- Finding the closest dictionary word
- Post-processing recognized text
Given two strings source and target, find the minimum number of operations required to convert source to target. The allowed operations are:
- Insert a character
- Delete a character
- Replace a character
Constraints
- Strings contain lowercase English letters only
Example
source = "kitten", target = "sitting"
3
- Inputs:
sourceis the OCR reading"kitten"(6 letters) andtargetis the intended word"sitting"(7 letters). Each insert, delete or replace costs exactly 1. - Line the words up: k/s, i/i, t/t, t/t, e/i, n/n, and
"sitting"has one extra g at the end. Four positions already agree and cost nothing. - Count the edits: replace k with s (sitten), replace e with i (sittin), insert g (sitting). That is operations.
- Why not fewer? The lengths differ by , so at least one insertion is unavoidable. Even after it, the letters k and e have no matching letter in the right place of
"sitting", and each mismatch needs its own edit. So 3 is the minimum, and the output is3. - Notice: the answer is a single non-negative integer, never larger than the longer string's length. Identical strings give 0. If one string is empty, the answer is just the other string's length (an empty string to "abc" needs 3 inserts).