Interleaving String
Problem Statement
You get three strings, s1, s2 and s3. Decide whether s3 can be made by interleaving s1 and s2.
An interleaving takes letters from s1 and s2, one at a time, so that every letter of s3 comes from exactly one of them. The letters of s1 must appear in their original order, and so must the letters of s2.
Three strings s1, s2 and s3.
true if s3 is an interleaving of s1 and s2, otherwise false.
Cut s1 into aa, bc, c and s2 into dbbc, a. Then alternate the pieces: aa + dbbc + bc + a + c = aadbbcbcac.
The a at position 6 of s3 must come from s2. But s2 has a c before its a, and s3 has no c before position 6.
Both strings are empty, so the empty string is the only interleaving.
- • 0 ≤ s1.length, s2.length ≤ 100
- • 0 ≤ s3.length ≤ 200
- • s1, s2 and s3 consist of lowercase English letters.
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
Recurse on (i, j): the last letter placed came from s1 or from s2, so try both
dp[i][j] = can the first i letters of s1 and the first j letters of s2 make the first i + j letters of s3
Keep one row over s2 and update it for each letter of s1; O(M) extra space
Let can(i, j) say whether the first i letters of s1 and the first j letters of s2 can make the first i + j letters of s3. The last letter placed is s3[i + j − 1]. It came from s1 when s1[i − 1] equals it and can(i − 1, j) is true. It came from s2 when s2[j − 1] equals it and can(i, j − 1) is true. The answer is can for the full lengths, after the length check.
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.