Bird
Raised Fist0
Interview Prepchallenge-problemshardGoogleAmazonMicrosoftFacebook

Edit Distance

Choose your preparation mode4 modes available
</>
IDE
def minDistance(word1: str, word2: str) -> int:public int minDistance(String word1, String word2)int minDistance(string word1, string word2)function minDistance(word1, word2)
def minDistance(word1: str, word2: str) -> int:
    # Write your solution here
    pass
class Solution {
    public int minDistance(String word1, String word2) {
        // Write your solution here
        return 0;
    }
}
#include <string>
using namespace std;

int minDistance(string word1, string word2) {
    // Write your solution here
    return 0;
}
function minDistance(word1, word2) {
    // Write your solution here
}
Coming soon
0/10
Common Bugs to Avoid
Wrong: 0Always returning 0 without computing edit distance; ignoring differences between strings.✅ Implement dp recurrence considering insert, delete, and replace operations.
Wrong: length of longer stringAssuming edit distance equals length of longer string without considering replacements or matches.✅ Use dp to find minimal operations including replacements and matches.
Wrong: off-by-one errors causing incorrect dp indexingIncorrect dp table indexing leading to wrong subproblem results.✅ Align dp indices with string indices carefully; dp[i][j] corresponds to prefixes of length i and j.
Wrong: TLEUsing brute force recursion without memoization or dp.✅ Implement bottom-up or top-down dp with memoization to achieve O(m*n) time.
✓
Test Cases
t1_01basic
Input{"word1":"horse","word2":"ros"}
Expected3

horse -> rorse (replace 'h' with 'r') -> rose (remove 'r') -> ros (remove 'e')

t1_02basic
Input{"word1":"intention","word2":"execution"}
Expected5

intention -> inention (delete 't') -> enention (replace 'i' with 'e') -> exention (replace 'n' with 'x') -> executtion (replace 'n' with 'c') -> execution (delete 't')

t2_01edge
Input{"word1":"","word2":""}
Expected0

Both strings empty, no operations needed.

t2_02edge
Input{"word1":"a","word2":""}
Expected1

One string empty, other has one character; one delete operation needed.

t2_03edge
Input{"word1":"abc","word2":"abc"}
Expected0

Strings are identical; no operations needed.

t2_04edge
Input{"word1":"a","word2":"b"}
Expected1

Strings differ by one character; one replacement needed.

t3_01corner
Input{"word1":"abc","word2":"acb"}
Expected2

Transform 'abc' to 'acb' requires two operations: replace 'b' with 'c' and replace 'c' with 'b'.

t3_02corner
Input{"word1":"aaa","word2":"aaaa"}
Expected1

Only one insertion needed to convert 'aaa' to 'aaaa'.

t3_03corner
Input{"word1":"abcde","word2":"abfde"}
Expected1

Only one replacement needed: 'c' replaced by 'f'.

t4_01performance
Input{"word1":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","word2":"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"}
⏱ Performance - must finish in 2000ms

n=100, O(m*n) = 10,000 operations expected to complete within 2 seconds.

Practice

(1/5)
1. You are given a string and need to count all substrings that read the same forwards and backwards. Which approach guarantees an optimal time and space solution for this problem?
easy
A. Use a brute force approach checking every substring with nested loops and palindrome verification.
B. Use a longest common subsequence DP approach comparing the string with its reverse.
C. Expand around each character and each pair of characters to count palindromes in O(n²) time and O(1) space.
D. Apply a greedy approach by extending palindromes only when characters match at the ends.

Solution

  1. Step 1: Understand problem constraints

    The problem requires counting all palindromic substrings efficiently, not just longest palindromes.
  2. Step 2: Evaluate approaches

    Brute force is correct but inefficient (O(n³)). LCS DP finds longest palindrome but not count of all substrings. Greedy fails on nested palindromes. Expanding around centers counts all palindromes in O(n²) time and O(1) space.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Expanding around centers covers odd and even length palindromes efficiently [OK]
Hint: Expanding centers counts all palindromes in O(n²) time [OK]
Common Mistakes:
  • Confusing longest palindrome with counting all palindromic substrings
2. You are given two sequences and need to find the length of the longest sequence that appears in both sequences in the same order, but not necessarily contiguously. Which algorithmic approach guarantees finding the optimal solution efficiently?
easy
A. A greedy algorithm that matches characters from left to right whenever they are equal
B. Divide and conquer by splitting sequences and merging results without overlapping
C. Sorting both sequences and then finding the longest increasing subsequence
D. Dynamic programming that builds solutions for smaller prefixes and combines them

Solution

  1. Step 1: Understand the problem requirements

    The problem requires finding a subsequence common to both sequences, preserving order but not necessarily contiguous, which is a classic dynamic programming problem.
  2. Step 2: Evaluate algorithm suitability

    Greedy approaches fail because they can miss longer subsequences by making local choices. Sorting changes order and breaks subsequence constraints. Divide and conquer without overlapping subproblems cannot efficiently combine partial results. Dynamic programming systematically explores all prefixes and stores intermediate results, ensuring optimality.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    DP is the standard approach for LCS problems [OK]
Hint: LCS requires DP, greedy fails on order constraints [OK]
Common Mistakes:
  • Assuming greedy matching always works
  • Confusing subsequence with substring
  • Trying to sort sequences to simplify
3. Identify the bug in the following space-optimized DP code for longest palindromic subsequence:
medium
A. Line updating dp[j] inside the inner loop
B. Line updating prev variable
C. Line initializing dp with zeros instead of ones
D. Line comparing s[i] and s[j]

Solution

  1. Step 1: Check dp initialization

    dp should be initialized with 1s because every single character is a palindrome of length 1.
  2. Step 2: Consequence of zero initialization

    Initializing dp with zeros causes palindromes of length 1 to be counted as 0, leading to incorrect results.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Correct initialization is dp = [1]*n, not zeros [OK]
Hint: dp[i][i] = 1 base case must be set [OK]
Common Mistakes:
  • Forgetting base case initialization
  • Overwriting dp too early
  • Misusing prev variable
4. The following code attempts to implement space-optimized DP for regex matching. Which line contains a subtle bug that causes incorrect results on some inputs?
def isMatch(s: str, p: str) -> bool:
    m, n = len(s), len(p)
    dp = [False] * (n + 1)
    dp[0] = True
    for j in range(2, n + 1):
        if p[j - 1] == '*':
            dp[j] = dp[j - 2]
    for i in range(1, m + 1):
        prev = dp[0]
        dp[0] = False
        for j in range(1, n + 1):
            temp = dp[j]
            if p[j - 1] == '*':
                dp[j] = dp[j] or dp[j - 2]
                if p[j - 2] == '.' or p[j - 2] == s[i - 1]:
                    dp[j] = dp[j] or prev
            else:
                dp[j] = prev and (p[j - 1] == '.' or p[j - 1] == s[i - 1])
            prev = temp
    return dp[n]
medium
A. Line: dp[0] = False inside the outer loop
B. Line: for j in range(1, n + 1): iterating forwards instead of backwards
C. Line: prev = dp[0] before inner loop starts
D. Line: dp[j] = dp[j] or dp[j - 2] inside the '*' handling block

Solution

  1. Step 1: Understand dp array update dependencies

    When updating dp[j], dp[j - 2] must not be overwritten before use. Iterating forwards overwrites dp[j - 2] too early.
  2. Step 2: Identify iteration direction bug

    Iterating forwards causes dp[j - 2] to be stale or overwritten, leading to incorrect matches. Iterating backwards avoids this.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Known bug in space-optimized regex DP is forward iteration [OK]
Hint: DP updates with '*' require backward iteration to preserve dp[j-2] [OK]
Common Mistakes:
  • Assuming forward iteration is safe in space-optimized DP
5. Examine the following buggy code for shortest common supersequence length. Which line contains the subtle bug that causes incorrect results when one input string is empty?
medium
A. Line 7: Condition comparing str1[i-1] and str2[j-1]
B. Line 5: Initialization of curr with [i] + [0]*n
C. Line 10: Updating prev = curr
D. Line 3: Initialization of prev with zeros instead of range

Solution

  1. Step 1: Check base case initialization of prev array

    Prev should be initialized as range(n+1) to represent base case when str1 is empty; zeros cause incorrect base lengths.
  2. Step 2: Confirm other lines correctly implement DP transitions

    Lines initializing curr, comparing characters, and updating prev are correct.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Incorrect base initialization leads to wrong results when one string is empty [OK]
Hint: Base case initialization must reflect empty string lengths [OK]
Common Mistakes:
  • Initializing dp arrays with zeros instead of incremental ranges
  • Mixing up indices in conditions
  • Forgetting to update prev array
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