Return the shortest string that has both str1 and str2 as subsequences. Any valid answer of minimum length is accepted.
Before you code
Its length is len(str1) + len(str2) − LCS, because the common subsequence only needs to appear once. Building the string itself requires the full LCS table and a walk back.
Hints
- Fill the LCS table for the two strings.
- Walk back from the bottom-right: on a match, emit the character once and move diagonally; otherwise emit the character from the side you move away from.
- When one string is used up, emit the rest of the other. Reverse at the end.
Production & complexity notes
When solving Shortest common supersequence on LeetCode (hard), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Rebuilding the answer and saving memory to reinforce the underlying pattern.
What it practices
Reconstructing a solution from a DP table, from Rebuilding the answer and saving memory.