Bird
Raised Fist0
Interview Prepdp-lcs-stringhardGoogleAmazon

Shortest Common Supersequence

Choose your preparation mode4 modes available
📋
Problem

Imagine merging two versions of a document with minimal redundancy, preserving the order of characters from both versions.

Given two strings str1 and str2, return the shortest string that has both str1 and str2 as subsequences. If multiple answers exist, return any of them.

1 ≤ str1.length, str2.length ≤ 1000str1 and str2 consist of lowercase English letters
Edge cases: One string empty → output is the other stringBoth strings identical → output is the string itselfNo common characters → output is concatenation of both strings
</>
IDE
def scs(str1: str, str2: str) -> str:public String scs(String str1, String str2)string scs(string str1, string str2)function scs(str1, str2)
def scs(str1, str2):
    # Write your solution here
    pass
class Solution {
    public String scs(String str1, String str2) {
        // Write your solution here
        return "";
    }
}
#include <string>
using namespace std;

string scs(string str1, string str2) {
    // Write your solution here
    return "";
}
function scs(str1, str2) {
    // Write your solution here
}
Coming soon
0/9
Common Bugs to Avoid
Wrong: abcabcGreedy approach concatenating strings without considering LCS.✅ Use DP to find LCS and merge strings around it instead of simple concatenation.
Wrong: abacbIncorrect DP indexing causing wrong character order or missing characters.✅ Carefully implement DP with correct 1-based indexing and reconstruct supersequence accordingly.
Wrong: aabbccFailing to preserve subsequence order with repeated characters.✅ Track indices properly in DP and merge repeated characters in correct order.
Wrong: abcReturning shorter string when one input is empty instead of the other.✅ Return the non-empty string when the other is empty.
Wrong: abcdefConcatenating strings without checking for common subsequences.✅ Check for LCS and merge accordingly to minimize length.
✓
Test Cases
t1_01basic
Input{"str1":"abac","str2":"cab"}
Expected5

One shortest common supersequence is "cabac" which contains both "abac" and "cab" as subsequences.

t1_02basic
Input{"str1":"abc","str2":"ac"}
Expected3

"abc" is a shortest common supersequence containing both "abc" and "ac" as subsequences.

t2_01edge
Input{"str1":"","str2":"abc"}
Expected3

One string empty, so output is the other string.

t2_02edge
Input{"str1":"aaa","str2":"aaa"}
Expected3

Both strings identical, so output is the string itself.

t2_03edge
Input{"str1":"abc","str2":"def"}
Expected6

No common characters, so output is concatenation of both strings.

t3_01corner
Input{"str1":"abc","str2":"acb"}
Expected4

Greedy approach picking characters from one string first fails; correct SCS is "acbc".

t3_02corner
Input{"str1":"aabcc","str2":"dbbca"}
Expected8

Handles repeated characters and correct subsequence order; output "adbbccca" is shortest common supersequence.

t3_03corner
Input{"str1":"abcde","str2":"ace"}
Expected5

Tests off-by-one errors in DP indexing; output "abcde" is shortest common supersequence.

t4_01performance
Input{"_description":"n=1000 at constraint boundary - executor generates this input"}
⏱ Performance - must finish in 2000ms

Input size n=1000, O(m*n) DP solution must complete within 2 seconds.

Practice

(1/5)
1. You need to transform one string into another using the minimum number of insertions, deletions, and substitutions. Which algorithmic approach guarantees finding the optimal solution efficiently?
easy
A. Dynamic Programming that builds solutions for all prefixes of both strings
B. Greedy algorithm that replaces characters whenever they differ
C. Divide and conquer by splitting strings at midpoint and solving recursively
D. Backtracking all possible sequences of edits without memoization

Solution

  1. Step 1: Understand problem requires minimal edits including insertions, deletions, and substitutions

    These operations depend on overlapping subproblems, making DP suitable.
  2. Step 2: Identify approach that solves all subproblems efficiently

    Dynamic Programming computes minimal edits for all prefixes, ensuring optimality and polynomial time complexity.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    DP covers all prefix pairs systematically [OK]
Hint: Optimal edit distance requires DP over all prefix pairs [OK]
Common Mistakes:
  • Assuming greedy always works
  • Thinking divide and conquer alone suffices
  • Ignoring overlapping subproblems
2. You are given a string and need to partition it into substrings such that each substring is a palindrome. The goal is to minimize the number of cuts needed to achieve this. Which algorithmic approach guarantees an optimal solution for this problem?
easy
A. Pure recursion checking all partitions without memoization
B. Greedy approach that cuts whenever a palindrome substring is found from the start
C. Dynamic Programming using a 1D dp array with palindrome center expansion to minimize cuts
D. Sorting substrings by length and choosing the longest palindrome first

Solution

  1. Step 1: Understand problem constraints

    The problem requires minimizing cuts so that every substring is a palindrome, which is a classic optimization problem.
  2. Step 2: Identify algorithmic approach

    Greedy or sorting approaches fail because palindrome partitions depend on global structure, not local choices. Pure recursion is correct but inefficient. The optimal approach uses DP with palindrome center expansion to efficiently find minimal cuts.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    DP with palindrome center expansion is known optimal [OK]
Hint: Optimal solution uses DP with palindrome center expansion [OK]
Common Mistakes:
  • Assuming greedy cuts yield minimal partitions
  • Ignoring palindrome checks in DP
  • Using pure recursion without memoization
3. Suppose the problem is modified so that characters can be deleted multiple times (i.e., you can delete the same character repeatedly if it appears multiple times), and you want to find the minimum number of deletions to make the two strings equal. Which modification to the DP approach is necessary to handle this variant correctly?
hard
A. Use the same DP but add a third dimension to track deletion counts
B. Switch to a greedy approach deleting all duplicates first
C. No change needed; the original DP already accounts for multiple deletions of the same character
D. Modify the DP to allow reuse of characters by changing the recurrence to consider repeated deletions

Solution

  1. Step 1: Understand repeated deletions mean characters can be deleted multiple times

    This breaks the assumption that each character is deleted at most once.
  2. Step 2: Modify DP recurrence to consider repeated deletions

    DP must allow transitions that delete characters multiple times, possibly by adjusting state or recurrence to reflect reuse.
  3. Step 3: Recognize original DP does not handle repeated deletions explicitly

    Original DP assumes each character is deleted once; greedy or no change fail to capture repeated deletions correctly.
  4. Final Answer:

    Option D -> Option D
  5. Quick Check:

    Repeated deletions require recurrence changes, not just dimensions or greedy [OK]
Hint: Repeated deletions -> recurrence must allow reuse [OK]
Common Mistakes:
  • Assuming original DP suffices
  • Adding unnecessary DP dimensions
  • Using greedy incorrectly
4. Suppose the problem is modified so that characters from s1 and s2 can be reused any number of times to form s3. Which of the following algorithmic changes correctly adapts the DP solution to this new requirement?
hard
A. Use the same DP but allow transitions to stay at the same indices in s1 or s2 when characters match, enabling reuse
B. No change needed; the original DP already handles reuse implicitly
C. Change the DP to a shortest path problem in a graph where edges represent character matches with reuse allowed
D. Modify the DP to consider infinite loops by adding a visited set to avoid cycles in recursion

Solution

  1. Step 1: Understand reuse impact

    Allowing reuse means indices in s1 and s2 can stay the same or move forward, potentially causing cycles.
  2. Step 2: Adapt algorithm

    To avoid infinite recursion or loops, the DP or recursion must track visited states to prevent cycles.
  3. Step 3: Evaluate options

    Modify the DP to consider infinite loops by adding a visited set to avoid cycles in recursion correctly adds a visited set to recursion to handle cycles; others either do not prevent cycles or incorrectly claim no change is needed.
  4. Final Answer:

    Option D -> Option D
  5. Quick Check:

    Cycle detection is essential when reuse is allowed to ensure termination [OK]
Hint: Reuse allows cycles; track visited states to avoid infinite loops [OK]
Common Mistakes:
  • Assuming original DP handles reuse without modification
  • Trying to model reuse with simple DP transitions without cycle checks
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