Bird
Raised Fist0
Interview Prepdp-lcs-stringmediumAmazonGoogle

Delete Operation for Two Strings

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, word2):
    # 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: 0Returning zero deletions for all inputs, ignoring differences between strings.✅ Implement DP to compute LCS and calculate deletions as sum of lengths minus twice LCS length.
Wrong: len(word1) or len(word2) onlyOnly deleting characters from one string, ignoring the other string's deletions.✅ Calculate deletions as len(word1) + len(word2) - 2 * LCS(word1, word2).
Wrong: Incorrect value due to greedy matchingUsing greedy approach to match characters instead of DP for LCS.✅ Use DP table to find maximum LCS length instead of greedy matching.
Wrong: TLE or timeoutUsing pure recursion without memoization causing exponential time complexity.✅ Implement memoization or bottom-up DP to achieve O(m*n) time complexity.
Wrong: Off-by-one errors causing wrong LCS lengthIncorrect indexing in DP table or string character comparisons.✅ Carefully index DP table and strings; ensure loops and conditions are correct.
✓
Test Cases
t1_01basic
Input{"word1":"sea","word2":"eat"}
Expected2

Delete 's' from "sea" and 't' from "eat" to make both strings "ea".

t1_02basic
Input{"word1":"leetcode","word2":"etco"}
Expected4

LCS is "etco" with length 4; deletions = 8 + 4 - 2*4 = 4.

t2_01edge
Input{"word1":"","word2":"abc"}
Expected3

One string empty, so all characters of the other must be deleted.

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

Both strings identical; no deletions needed.

t2_03edge
Input{"word1":"abc","word2":"def"}
Expected6

No common characters; must delete all characters from both strings.

t2_04edge
Input{"word1":"aaa","word2":"aa"}
Expected1

LCS is "aa" length 2; deletions = 3 + 2 - 2*2 = 1.

t3_01corner
Input{"word1":"aabbcc","word2":"abcabc"}
Expected4

LCS is "abcc" or "aabc" with length 4; deletions = 6 + 6 - 2*4 = 4.

t3_02corner
Input{"word1":"abc","word2":"abcabc"}
Expected3

LCS is "abc" length 3; deletions = 3 + 6 - 2*3 = 3.

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

LCS is "abde" length 4; deletions = 5 + 5 - 2*4 = 2.

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

n=500, O(m*n) DP must complete within 2s.

Practice

(1/5)
1. Consider the following Python function implementing the space-optimized DP for Minimum ASCII Delete Sum:
def minimumDeleteSum(s1: str, s2: str) -> int:
    m, n = len(s1), len(s2)
    dp = [0] * (n + 1)
    for j in range(1, n + 1):
        dp[j] = dp[j-1] + ord(s2[j-1])
    for i in range(1, m + 1):
        prev = dp[0]
        dp[0] += ord(s1[i-1])
        for j in range(1, n + 1):
            temp = dp[j]
            if s1[i-1] == s2[j-1]:
                dp[j] = prev
            else:
                dp[j] = min(dp[j] + ord(s1[i-1]), dp[j-1] + ord(s2[j-1]))
            prev = temp
    return dp[n]

print(minimumDeleteSum("sea", "eat"))
What is the final returned value for input s1 = "sea" and s2 = "eat"?
easy
A. 231
B. 197
C. 314
D. 259

Solution

  1. Step 1: Initialize dp array for s2="eat"

    dp after first loop: dp=[0, 101('e'), 101+97('a')=198, 198+116('t')=314]
  2. Step 2: Iterate over s1="sea" updating dp

    After processing 's': dp=[115, 101, 198, 314] After 'e': dp=[216, 115, 198, 314] After 'a': dp final dp[n]=231
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Matches known example output 231 [OK]
Hint: Trace dp array updates carefully for each character [OK]
Common Mistakes:
  • Off-by-one errors in indexing dp or strings
2. The following code attempts to implement the space-optimized LCS algorithm. Which line contains a subtle bug that can cause incorrect results on some inputs?
medium
A. Line 7: for j in range(1, n + 1): # iterating forwards
B. Line 5: for i in range(1, m + 1):
C. Line 9: if text1[i - 1] == text2[j - 1]:
D. Line 12: prev = temp

Solution

  1. Step 1: Identify iteration order in inner loop

    The inner loop iterates forwards (j=1 to n), which causes dp[j-1] to be overwritten before it is used in the max calculation.
  2. Step 2: Understand impact of forward iteration

    Because dp[j-1] is updated before dp[j], the algorithm uses updated values instead of previous iteration's values, leading to incorrect LCS length.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Inner loop must iterate backwards to preserve dp[j-1] values [OK]
Hint: Inner loop must run backwards to avoid overwriting dp array [OK]
Common Mistakes:
  • Iterating inner loop forwards in space optimized DP
  • Mixing up indices in character comparison
  • Incorrect initialization of prev variable
3. Suppose you want to find the length of the longest common subsequence between two strings, but now characters from the second string can be reused multiple times. Which modification to the standard LCS algorithm correctly handles this scenario?
hard
A. Use the same DP but allow dp[j] to depend on dp[j] itself without decrementing j in inner loop
B. Change the inner loop to iterate forwards and update dp[j] using dp[j] and dp[j-1] to allow reuse
C. Use a greedy approach matching characters from left to right allowing reuse
D. Use a bottom-up DP with a 2D table but ignore previous matches to allow reuse

Solution

  1. Step 1: Understand reuse impact

    Allowing reuse of characters in the second string means dp[j] can be updated based on dp[j] itself (not only dp[j-1]) and the inner loop must run forwards to propagate reuse correctly.
  2. Step 2: Identify correct DP iteration

    Iterating forwards in the inner loop allows dp[j] to accumulate matches with reuse, unlike standard LCS which iterates backwards to avoid reuse.
  3. Step 3: Evaluate other options

    Greedy fails to find optimal subsequence. Ignoring previous matches breaks DP correctness. Using 2D DP without reuse logic is insufficient.
  4. Final Answer:

    Option B -> Option B
  5. Quick Check:

    Forward iteration in inner loop enables reuse of characters [OK]
Hint: Forward inner loop iteration enables reuse in DP [OK]
Common Mistakes:
  • Using backward iteration preventing reuse
  • Trying greedy approach
  • Ignoring DP state dependencies
4. Suppose you want to find the longest common substring between two strings, but now substrings can be formed by reusing characters multiple times (i.e., characters can be repeated any number of times). Which modification to the DP approach correctly handles this variant?
hard
A. Use the same DP but allow dp[j] to accumulate without resetting to zero on mismatch
B. Modify DP to allow transitions from dp[j] and dp[j-1] to handle reuse, iterating forward over j
C. Use a suffix automaton or suffix trie data structure instead of DP
D. Apply longest common subsequence DP since reuse allows gaps and repeats

Solution

  1. Step 1: Understand reuse means characters can be matched multiple times

    Longest common substring with reuse breaks contiguity and requires allowing repeated matches.
  2. Step 2: Modify DP to allow reuse by iterating forward and allowing dp[j] to build on itself

    Iterating forward over j and allowing dp[j] to depend on dp[j] and dp[j-1] enables reuse of characters multiple times.
  3. Step 3: Recognize other options fail

    Resetting dp on mismatch breaks reuse, suffix automaton is complex but not DP, subsequence DP allows gaps but not reuse as described.
  4. Final Answer:

    Option B -> Option B
  5. Quick Check:

    Forward iteration with reuse transitions correctly models repeated characters [OK]
Hint: Reuse requires forward iteration and dp[j] depending on itself [OK]
Common Mistakes:
  • Not resetting dp breaks reuse
  • Using subsequence DP incorrectly
  • Ignoring iteration order for reuse
5. Suppose you want to find the longest palindromic subsequence in a string where characters can be reused unlimited times. Which modification to the DP approach correctly handles this variant?
hard
A. Modify DP to consider infinite reuse by allowing i to stay fixed while j moves, and vice versa
B. Use a greedy approach selecting matching characters repeatedly from both ends
C. Use the same DP but allow indices i and j to move independently without restriction
D. This problem reduces to longest palindromic substring, so use Manacher's algorithm

Solution

  1. Step 1: Understand reuse means characters can be counted multiple times

    Standard LPS counts each character once; reuse requires relaxing index movement constraints.
  2. Step 2: Modify DP transitions to allow staying at i or j to reuse characters

    DP must consider cases where i or j does not advance to reuse characters, effectively allowing repeated use.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Allowing indices to stay or move independently models reuse correctly [OK]
Hint: Reuse means relaxing index movement in DP transitions [OK]
Common Mistakes:
  • Using greedy approach
  • Confusing substring with subsequence
  • Applying substring algorithms incorrectly
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