v9.1.1
Menu

Edit Distance for OCR Correction

mediumPRODynamic ProgrammingDynamic Programming, StringCV - DSA

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:

  1. Insert a character
  2. Delete a character
  3. Replace a character

Constraints

  • 0≤len(source),len(target)≤5000 \leq len(source), len(target) \leq 500
  • Strings contain lowercase English letters only

Example

Input
source = "kitten", target = "sitting"
Output
3
Reasoning
  • Inputs: source is the OCR reading "kitten" (6 letters) and target is 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 1+1+1=31 + 1 + 1 = 3 operations.
  • Why not fewer? The lengths differ by 7−6=17 - 6 = 1, 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 is 3.
  • 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).

Learn this in

More from CV - DSA

PRO

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test results

Sign in to run your code against the test cases.