TRT
Sign in
hardAdvancedLeetCode#LCS table#reconstruction

Shortest common supersequence

Build the shortest string containing both inputs as subsequences by walking back through an LCS table.

The Runtime Theory Team1 min read
Taught inRebuilding the answer and saving memoryPro — members onlyA DP table holds the value of the best solution, not the solution itself. Walking back through the table recovers the choices. When only the value is needed, keeping one or two rows cuts memory from O(n × m) to O(m).
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

instr1 = abac, str2 = cab

outcabac (any shortest answer)

instr1 = aaaaaaaa, str2 = aaaaaaaa

outaaaaaaaa

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

  1. Fill the LCS table for the two strings.
  2. 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.
  3. 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.

Not started

Sign in to save your learning progress.

Sign in to save