Given two strings str1 and str2, return the shortest string that has both str1 and str2 as subsequences. If there are multiple valid strings, return any of them.
A string s is a subsequence of string t if deleting some number of characters from t (possibly 0) results in the string s.
Example 1:
Input: str1 = "abac", str2 = "cab"
Output: "cabac"
Explanation:
str1 = "abac" is a subsequence of "cabac" because we can delete the first "c".
str2 = "cab" is a subsequence of "cabac" because we can delete the last "ac".
The answer provided is the shortest such string that satisfies these properties.
Problem summary: Given two strings str1 and str2, return the shortest string that has both str1 and str2 as subsequences. If there are multiple valid strings, return any of them. A string s is a subsequence of string t if deleting some number of characters from t (possibly 0) results in the string s.
Baseline thinking
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Dynamic Programming
Example 1
"abac"
"cab"
Example 2
"aaaaaaaa"
"aaaaaaaa"
Related Problems
Longest Common Subsequence (longest-common-subsequence)
Shortest String That Contains Three Strings (shortest-string-that-contains-three-strings)
Step 02
Core Insight
What unlocks the optimal approach
We can find the length of the longest common subsequence between str1[i:] and str2[j:] (for all (i, j)) by using dynamic programming.
We can use this information to recover the shortest common supersequence.
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03
Algorithm Walkthrough
Iteration Checklist
Define state (indices, window, stack, map, DP cell, or recursion frame).
Apply one transition step and update the invariant.
Record answer candidate when condition is met.
Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04
Edge Cases
Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Largest constraint values
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05
Full Annotated Code
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1092: Shortest Common Supersequence
class Solution {
public String shortestCommonSupersequence(String str1, String str2) {
int m = str1.length(), n = str2.length();
int[][] f = new int[m + 1][n + 1];
for (int i = 1; i <= m; ++i) {
for (int j = 1; j <= n; ++j) {
if (str1.charAt(i - 1) == str2.charAt(j - 1)) {
f[i][j] = f[i - 1][j - 1] + 1;
} else {
f[i][j] = Math.max(f[i - 1][j], f[i][j - 1]);
}
}
}
int i = m, j = n;
StringBuilder ans = new StringBuilder();
while (i > 0 || j > 0) {
if (i == 0) {
ans.append(str2.charAt(--j));
} else if (j == 0) {
ans.append(str1.charAt(--i));
} else {
if (f[i][j] == f[i - 1][j]) {
ans.append(str1.charAt(--i));
} else if (f[i][j] == f[i][j - 1]) {
ans.append(str2.charAt(--j));
} else {
ans.append(str1.charAt(--i));
--j;
}
}
}
return ans.reverse().toString();
}
}
// Accepted solution for LeetCode #1092: Shortest Common Supersequence
func shortestCommonSupersequence(str1 string, str2 string) string {
m, n := len(str1), len(str2)
f := make([][]int, m+1)
for i := range f {
f[i] = make([]int, n+1)
}
for i := 1; i <= m; i++ {
for j := 1; j <= n; j++ {
if str1[i-1] == str2[j-1] {
f[i][j] = f[i-1][j-1] + 1
} else {
f[i][j] = max(f[i-1][j], f[i][j-1])
}
}
}
ans := []byte{}
i, j := m, n
for i > 0 || j > 0 {
if i == 0 {
j--
ans = append(ans, str2[j])
} else if j == 0 {
i--
ans = append(ans, str1[i])
} else {
if f[i][j] == f[i-1][j] {
i--
ans = append(ans, str1[i])
} else if f[i][j] == f[i][j-1] {
j--
ans = append(ans, str2[j])
} else {
i, j = i-1, j-1
ans = append(ans, str1[i])
}
}
}
for i, j = 0, len(ans)-1; i < j; i, j = i+1, j-1 {
ans[i], ans[j] = ans[j], ans[i]
}
return string(ans)
}
# Accepted solution for LeetCode #1092: Shortest Common Supersequence
class Solution:
def shortestCommonSupersequence(self, str1: str, str2: str) -> str:
m, n = len(str1), len(str2)
f = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(1, m + 1):
for j in range(1, n + 1):
if str1[i - 1] == str2[j - 1]:
f[i][j] = f[i - 1][j - 1] + 1
else:
f[i][j] = max(f[i - 1][j], f[i][j - 1])
ans = []
i, j = m, n
while i or j:
if i == 0:
j -= 1
ans.append(str2[j])
elif j == 0:
i -= 1
ans.append(str1[i])
else:
if f[i][j] == f[i - 1][j]:
i -= 1
ans.append(str1[i])
elif f[i][j] == f[i][j - 1]:
j -= 1
ans.append(str2[j])
else:
i, j = i - 1, j - 1
ans.append(str1[i])
return ''.join(ans[::-1])
// Accepted solution for LeetCode #1092: Shortest Common Supersequence
struct Solution;
impl Solution {
fn shortest_common_supersequence(str1: String, str2: String) -> String {
let s1: Vec<char> = str1.chars().collect();
let s2: Vec<char> = str2.chars().collect();
let n = s1.len();
let m = s2.len();
let mut dp = vec![vec![(' ', 0, std::usize::MAX, std::usize::MAX); m + 1]; n + 1];
for i in 0..n {
dp[i + 1][0] = (s1[i], i + 1, i, 0);
}
for j in 0..m {
dp[0][j + 1] = (s2[j], j + 1, 0, j);
}
for i in 0..n {
for j in 0..m {
if s1[i] == s2[j] {
dp[i + 1][j + 1] = (s1[i], dp[i][j].1 + 1, i, j);
} else {
if dp[i][j + 1].1 < dp[i + 1][j].1 {
dp[i + 1][j + 1] = (s1[i], dp[i][j + 1].1 + 1, i, j + 1);
} else {
dp[i + 1][j + 1] = (s2[j], dp[i + 1][j].1 + 1, i + 1, j);
}
}
}
}
let mut path = vec![];
let mut i = n;
let mut j = m;
while dp[i][j].0 != ' ' {
path.push(dp[i][j].0);
let next = dp[i][j];
i = next.2;
j = next.3;
}
path.into_iter().rev().collect()
}
}
#[test]
fn test() {
let str1 = "abac".to_string();
let str2 = "cab".to_string();
let res = "cabac".to_string();
assert_eq!(Solution::shortest_common_supersequence(str1, str2), res);
}
// Accepted solution for LeetCode #1092: Shortest Common Supersequence
function shortestCommonSupersequence(str1: string, str2: string): string {
const m = str1.length;
const n = str2.length;
const f = new Array(m + 1).fill(0).map(() => new Array(n + 1).fill(0));
for (let i = 1; i <= m; ++i) {
for (let j = 1; j <= n; ++j) {
if (str1[i - 1] == str2[j - 1]) {
f[i][j] = f[i - 1][j - 1] + 1;
} else {
f[i][j] = Math.max(f[i - 1][j], f[i][j - 1]);
}
}
}
let ans: string[] = [];
let i = m;
let j = n;
while (i > 0 || j > 0) {
if (i === 0) {
ans.push(str2[--j]);
} else if (j === 0) {
ans.push(str1[--i]);
} else {
if (f[i][j] === f[i - 1][j]) {
ans.push(str1[--i]);
} else if (f[i][j] === f[i][j - 1]) {
ans.push(str2[--j]);
} else {
ans.push(str1[--i]);
--j;
}
}
}
return ans.reverse().join('');
}
Step 06
Interactive Study Demo
Use this to step through a reusable interview workflow for this problem.
Press Step or Run All to begin.
Step 07
Complexity Analysis
Time
O(n × m)
Space
O(n × m)
Approach Breakdown
RECURSIVE
O(2ⁿ) time
O(n) space
Pure recursion explores every possible choice at each step. With two choices per state (take or skip), the decision tree has 2ⁿ leaves. The recursion stack uses O(n) space. Many subproblems are recomputed exponentially many times.
DYNAMIC PROGRAMMING
O(n × m) time
O(n × m) space
Each cell in the DP table is computed exactly once from previously solved subproblems. The table dimensions determine both time and space. Look for the state variables — each unique combination of state values is one cell. Often a rolling array can reduce space by one dimension.
Shortcut: Count your DP state dimensions → that’s your time. Can you drop one? That’s your space optimization.
Coach Notes
Common Mistakes
Review these before coding to avoid predictable interview regressions.
State misses one required dimension
Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.
Usually fails on: Correctness breaks on cases that differ only in hidden state.
Fix: Define state so each unique subproblem maps to one DP cell.