BLOGLLM Logo
Go Pro
Guest
Not signed in
All BlogsCoursesPracticeInterview prepSeriesTagsBookmarksPricing
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboardGames
Articles
Practice / Tokenization and NLP14 of 38 in topic

358. Compute Levenshtein edit distance

MediumTokenization and NLP

Spell checkers, fuzzy matching and word error rate for speech models all use edit distance: the fewest single-character inserts, deletes and substitutions to turn one string into another.

Write edit_distance(a, b) with dynamic programming. Each operation costs 1.

Functiondef edit_distance(a, b)

Example 1

Input: a = 'kitten', b = 'sitting'

Output: 3

Constraints

  • Python 3 standard library. Code runs in your browser.
  • Your code must pass all 4 tests to be accepted.
Hint 1

The distance between two prefixes can be built from the distances of slightly shorter prefixes, which makes this a dynamic programming table.

Hint 2

Let dp[i][j] be the distance between a[:i] and b[:j], start the first row and column with 0, 1, 2, ..., and fill each cell as the cheapest of delete, insert or substitute.

Hint 3

The cell rule is min(dp[i-1][j] + 1, dp[i][j-1] + 1, dp[i-1][j-1] + (a[i-1] != b[j-1])), and you can keep only the previous row to save memory.

Common mistakes
  • Comparing position by position (the buggy version) cannot handle an insertion, which shifts everything after it.
Understand the idea

Edit distance counts the fewest single-character inserts, deletes and substitutions needed to turn one string into another. Comparing position by position fails as soon as one character is inserted, because everything after it shifts. Dynamic programming fixes this: build a table where D[i][j] is the distance between the first i characters of a and the first j of b, and fill it from smaller prefixes.

Worked example

a = 'cat', b = 'cart'. Position by position, 't' vs 'r' and then a missing letter look like 2 changes, but the true answer is 1: insert 'r'. Small table for 'ab' to 'b': D[0][j] = j and D[i][0] = i. D[1][1] ('a' vs 'b') = 1. D[2][1] ('ab' vs 'b'): last characters match, so D[1][0] = 1. Answer 1 (delete 'a').

D[i][j] = min(D[i-1][j] + 1, D[i][j-1] + 1, D[i-1][j-1] + (0 if a_i == b_j else 1))

Spell checkers and word error rate for speech models use this.

Topics
Tokenization and NLP
Similar questions
  • Do one merge step of a BPE tokenizerMedium
  • Tokenize words with WordPiece greedy longest matchMedium
  • Build a vocabulary with special tokens, a minimum frequency and UNKMedium
  • Rank documents for a query with smoothed TF-IDF and cosine similarityMedium
All Tokenization and NLP problems
Report
358 / 903
Python 3solution.pyPython idle
1
2
3
4
def edit_distance(a, b):
# your code here
pass
​

Run checks these cases in your browser, no sign-in needed. Submit checks all 4 tests.

Ctrl/Cmd + Enter to run
© BlogLLM, Bengaluru, IndiaAboutTermsPrivacyRefundsDMCAContactRSS