Edit Distance Problem Levenshtein in DSA Typescript - Time & Space Complexity
We want to know how the time needed to find the edit distance between two words grows as the words get longer.
The question is: how does the number of steps change when the input words become bigger?
Analyze the time complexity of the following code snippet.
function levenshteinDistance(a: string, b: string): number {
const dp: number[][] = Array(a.length + 1).fill(null).map(() => Array(b.length + 1).fill(0));
for (let i = 0; i <= a.length; i++) dp[i][0] = i;
for (let j = 0; j <= b.length; j++) dp[0][j] = j;
for (let i = 1; i <= a.length; i++) {
for (let j = 1; j <= b.length; j++) {
if (a[i - 1] === b[j - 1]) dp[i][j] = dp[i - 1][j - 1];
else dp[i][j] = 1 + Math.min(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1]);
}
}
return dp[a.length][b.length];
}
This code calculates the minimum number of edits needed to change one word into another using a grid to store results.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Nested loops filling a 2D table of size (length of a + 1) by (length of b + 1).
- How many times: The inner loop runs for each character of the second word, and the outer loop runs for each character of the first word, so total steps multiply.
As the words get longer, the number of steps grows by multiplying their lengths.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 100 steps |
| 100 | About 10,000 steps |
| 1000 | About 1,000,000 steps |
Pattern observation: Doubling the length roughly squares the number of steps needed.
Time Complexity: O(m * n)
This means the time needed grows proportionally to the product of the lengths of the two words.
[X] Wrong: "The algorithm only depends on the longer word's length, so it's O(n)."
[OK] Correct: The algorithm compares every character of the first word with every character of the second, so both lengths matter and multiply the work.
Understanding this time complexity helps you explain how dynamic programming solves problems efficiently by storing results and avoiding repeated work.
"What if we used recursion without storing results? How would the time complexity change?"
Practice
Solution
Step 1: Understand the definition of Levenshtein distance
It counts the minimum edits (insertions, deletions, substitutions) needed to convert one string into another.Step 2: Compare with other options
Options A, C, and D describe different string metrics, not edit distance.Final Answer:
The minimum number of single-character edits to change one string into the other -> Option CQuick Check:
Edit distance = minimum edits [OK]
- Confusing edit distance with longest common substring
- Thinking it counts only substitutions, not insertions/deletions
- Assuming it measures similarity score instead of edit count
s1 and s2?Solution
Step 1: Identify correct parameter and return types
Levenshtein distance takes two strings and returns a number representing the edit distance.Step 2: Check each option's signature
function levenshtein(s1: string, s2: string): number matches the expected input and output types. Others mismatch types or return void.Final Answer:
function levenshtein(s1: string, s2: string): number -> Option AQuick Check:
Input strings, output number [OK]
- Using wrong parameter types like arrays or numbers
- Returning wrong types like boolean or void
- Using any type without specifying string inputs
function levenshtein(s1: string, s2: string): number {
const dp: number[][] = [];
for (let i = 0; i <= s1.length; i++) {
dp[i] = [i];
}
for (let j = 0; j <= s2.length; j++) {
dp[0][j] = j;
}
for (let i = 1; i <= s1.length; i++) {
for (let j = 1; j <= s2.length; j++) {
if (s1[i - 1] === s2[j - 1]) {
dp[i][j] = dp[i - 1][j - 1];
} else {
dp[i][j] = Math.min(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1]) + 1;
}
}
}
return dp[s1.length][s2.length];
}
console.log(levenshtein('kitten', 'sitting'))Solution
Step 1: Initialize DP table for 'kitten' and 'sitting'
DP table rows = 7, columns = 8. Base cases set for empty prefixes.Step 2: Fill DP table comparing characters and calculating minimum edits
Calculations show minimum edits needed to convert 'kitten' to 'sitting' is 3 (substitute 'k'->'s', 'e'->'i', insert 'g').Final Answer:
3 -> Option AQuick Check:
Levenshtein('kitten', 'sitting') = 3 [OK]
- Counting only substitutions, ignoring insertions/deletions
- Off-by-one errors in indexing strings
- Misreading the DP initialization steps
function levenshtein(s1: string, s2: string): number {
const dp: number[][] = [];
for (let i = 0; i < s1.length; i++) {
dp[i] = [i];
}
for (let j = 0; j < s2.length; j++) {
dp[0][j] = j;
}
for (let i = 1; i <= s1.length; i++) {
for (let j = 1; j <= s2.length; j++) {
if (s1[i - 1] === s2[j - 1]) {
dp[i][j] = dp[i - 1][j - 1];
} else {
dp[i][j] = Math.min(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1]) + 1;
}
}
}
return dp[s1.length][s2.length];
}Solution
Step 1: Check dp initialization loops
Loops run from 0 to less than length, but dp needs size length+1 to include empty prefix cases.Step 2: Correct loop ranges to include dp[s1.length] and dp[s2.length]
Change loops to run up to <= length to properly initialize dp edges.Final Answer:
The loops initializing dp should run up to <= length, not < length -> Option DQuick Check:
DP size must cover full string lengths [OK]
- Using < length instead of <= length in loops
- Incorrect string index comparisons causing off-by-one errors
- Returning wrong dp cell ignoring full string lengths
s1 = 'intention' and s2 = 'execution', what is the minimum edit distance using Levenshtein algorithm? Also, explain why this distance is correct.Solution
Step 1: Analyze transformations from 'intention' to 'execution'
Operations include substituting 'i'->'e', 'n'->'x', deleting 't', substituting 'n'->'c', substituting 't'->'u'. Counting these gives 5 edits.Step 2: Confirm minimal edits with DP approach
DP table confirms minimum edits needed is 5, as fewer edits cannot convert all differing characters.Final Answer:
5 -> Option BQuick Check:
Minimum edits = 5 for 'intention' to 'execution' [OK]
- Underestimating edits by ignoring deletions
- Counting only substitutions
- Misaligning characters causing wrong counts
Ready to prove it?
Pass the test and this pattern moves unknown
