Bird
Raised Fist0
DSA Typescriptprogramming~5 mins

Edit Distance Problem Levenshtein in DSA Typescript - Time & Space Complexity

Choose your learning style10 modes available
Time Complexity: Edit Distance Problem Levenshtein
O(m * n)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

As the words get longer, the number of steps grows by multiplying their lengths.

Input Size (n)Approx. Operations
10About 100 steps
100About 10,000 steps
1000About 1,000,000 steps

Pattern observation: Doubling the length roughly squares the number of steps needed.

Final Time Complexity

Time Complexity: O(m * n)

This means the time needed grows proportionally to the product of the lengths of the two words.

Common Mistake

[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.

Interview Connect

Understanding this time complexity helps you explain how dynamic programming solves problems efficiently by storing results and avoiding repeated work.

Self-Check

"What if we used recursion without storing results? How would the time complexity change?"

Practice

(1/5)
1. What does the Levenshtein edit distance between two strings measure?
easy
A. The maximum length of common substring between two strings
B. The number of characters that are the same in both strings
C. The minimum number of single-character edits to change one string into the other
D. The total length of both strings combined

Solution

  1. Step 1: Understand the definition of Levenshtein distance

    It counts the minimum edits (insertions, deletions, substitutions) needed to convert one string into another.
  2. Step 2: Compare with other options

    Options A, C, and D describe different string metrics, not edit distance.
  3. Final Answer:

    The minimum number of single-character edits to change one string into the other -> Option C
  4. Quick Check:

    Edit distance = minimum edits [OK]
Hint: Edit distance counts minimal edits to match strings [OK]
Common Mistakes:
  • Confusing edit distance with longest common substring
  • Thinking it counts only substitutions, not insertions/deletions
  • Assuming it measures similarity score instead of edit count
2. Which of the following TypeScript function signatures correctly represents a function to compute Levenshtein distance between two strings s1 and s2?
easy
A. function levenshtein(s1: string, s2: string): number
B. function levenshtein(s1: number, s2: number): string
C. function levenshtein(s1: string[], s2: string[]): boolean
D. function levenshtein(s1: any, s2: any): void

Solution

  1. Step 1: Identify correct parameter and return types

    Levenshtein distance takes two strings and returns a number representing the edit distance.
  2. 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.
  3. Final Answer:

    function levenshtein(s1: string, s2: string): number -> Option A
  4. Quick Check:

    Input strings, output number [OK]
Hint: Input strings, output number for edit distance [OK]
Common Mistakes:
  • Using wrong parameter types like arrays or numbers
  • Returning wrong types like boolean or void
  • Using any type without specifying string inputs
3. What is the output of the following TypeScript code snippet?
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'))
medium
A. 3
B. 4
C. 5
D. 6

Solution

  1. Step 1: Initialize DP table for 'kitten' and 'sitting'

    DP table rows = 7, columns = 8. Base cases set for empty prefixes.
  2. 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').
  3. Final Answer:

    3 -> Option A
  4. Quick Check:

    Levenshtein('kitten', 'sitting') = 3 [OK]
Hint: Trace DP table for small strings to find edit count [OK]
Common Mistakes:
  • Counting only substitutions, ignoring insertions/deletions
  • Off-by-one errors in indexing strings
  • Misreading the DP initialization steps
4. Identify the bug in this TypeScript implementation of Levenshtein distance:
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];
}
medium
A. The function should return dp[0][0] instead of dp[s1.length][s2.length]
B. The dp array should be initialized with zeros instead of indices
C. The comparison should be s1[i] === s2[j], not s1[i - 1] === s2[j - 1]
D. The loops initializing dp should run up to <= length, not < length

Solution

  1. 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.
  2. 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.
  3. Final Answer:

    The loops initializing dp should run up to <= length, not < length -> Option D
  4. Quick Check:

    DP size must cover full string lengths [OK]
Hint: Initialize DP arrays with length+1 for empty string cases [OK]
Common Mistakes:
  • Using < length instead of <= length in loops
  • Incorrect string index comparisons causing off-by-one errors
  • Returning wrong dp cell ignoring full string lengths
5. Given two strings s1 = 'intention' and s2 = 'execution', what is the minimum edit distance using Levenshtein algorithm? Also, explain why this distance is correct.
hard
A. 6
B. 5
C. 4
D. 7

Solution

  1. 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.
  2. Step 2: Confirm minimal edits with DP approach

    DP table confirms minimum edits needed is 5, as fewer edits cannot convert all differing characters.
  3. Final Answer:

    5 -> Option B
  4. Quick Check:

    Minimum edits = 5 for 'intention' to 'execution' [OK]
Hint: Count substitutions, insertions, deletions carefully [OK]
Common Mistakes:
  • Underestimating edits by ignoring deletions
  • Counting only substitutions
  • Misaligning characters causing wrong counts
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard