Russian Doll Envelopes
Problem Statement
You have a pile of envelopes. Each one has a width and a height. Envelope A can go inside envelope B only when both the width and the height of A are strictly smaller than those of B. You may not turn an envelope.
Nest as many envelopes as you can in one chain, one inside the next. Return the largest number of envelopes in such a chain.
envelopes: a list of [w, h] pairs, one pair for each envelope.
The largest number of envelopes in one nest.
The chain [2, 3] → [5, 4] → [6, 7] works: each envelope is strictly smaller in width and in height than the next one.
Equal envelopes do not fit inside each other, so only one of them can be used.
- • 1 ≤ envelopes.length ≤ 10^5
- • envelopes[i].length == 2
- • 1 ≤ wᵢ, hᵢ ≤ 10^5
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
Recurse: from the current outer envelope, try each envelope that fits strictly inside it; keep the longest chain
Sort by width, then height; dp[i] = 1 + the best dp[j] over earlier envelopes that fit strictly inside i
Sort by width ascending, height descending on ties; then the O(N log N) strict LIS on heights with lower_bound
Choose an outermost envelope, then recurse on the envelopes that fit strictly inside it on both sides. Try every choice and keep the longest chain. An envelope with an equal width or an equal height never fits, so the check is two strict comparisons.
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 — Longest Increasing Subsequence 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.