Shortest Common Supersequence
Problem Statement
You are given two strings str1 and str2. Build the shortest string that contains both of them as subsequences: each of them must be obtainable from the answer by deleting some letters. Return one shortest string. If there are several, any of them is accepted.
Two strings, str1 and str2.
A shortest string that has both str1 and str2 as subsequences.
abac is in cabac if you delete the first c. cab is in cabac if you delete the last ac. Nothing shorter contains both, so the length is 5.
The two strings are equal, so one copy is enough.
- • 1 ≤ str1.length, str2.length ≤ 1000
- • Lowercase English letters only.
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
Recurse on (i, j): write str1's letter, write str2's letter, or share a match; keep the shortest
Build the LCS table, then write the answer while walking back from (n, m)
Let scs(i, j) be the shortest string that contains str1[i..] and str2[j..] as subsequences. There are three ways to write the next letter: write str1's letter alone, write str2's letter alone, or, when the letters match, write one letter for both. Try every option and keep the shortest. When one string is used up, the rest of the other string is the answer.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like DP — Strings translate into production architectures and low-level memory mechanics.
Foundations: Object-Oriented Principles in C++23
Class invariants, pure virtual interfaces, and RAII smart pointers.
Food Delivery System (Zomato Architecture)
Real-world machine coding application of algorithms and design patterns.
Pointers vs References Deep Dive
Pointer arithmetic and memory layout under the hood.
Virtual Method Table (vtable) & Memory Layout
Polymorphism, vptr overhead, and multiple inheritance in memory.