Each envelope is given as [w, h], its width and height. One envelope fits inside another only when it is strictly narrower and strictly shorter. Envelopes cannot be turned sideways.
Return the largest number of envelopes you can nest, one inside the next, like a set of Russian dolls.
Example 1
Input: envelopes = [[4,6],[2,3],[4,5],[6,7],[3,2]] Output: 3 Why: 3×2 fits in 4×5, which fits in 6×7
2 more examples and the constraints
Example 2
Input: envelopes = [[2,2],[2,2]] Output: 1 Why: equal envelopes do not fit inside each other
Example 3
Input: envelopes = [[2,5],[4,3]] Output: 1 Why: 2×5 is narrower but taller, and turning it is not allowed
Constraints
- 1 ≤ number of envelopes ≤ 100,000
- Each envelope is [w, h] with 1 ≤ w, h ≤ 100,000
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Sort + DP over pairsO(n²)
- Sort + LIS with binary searchO(n log n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 100,000 envelopes | Verdict |
|---|---|---|---|
| Sort + DP over pairs | O(n²) | Clear, but times out | |
| Sort + LIS with binary search | O(n log n) | Best; one search per envelope |
n = number of envelopes.
Edge cases to test
- Equal envelopes. [[2,2],[2,2]] gives 1: fitting needs both sides strictly smaller.
- Same width, rising heights. [[3,1],[3,2],[3,3]] gives 1. Sorting heights upward here would wrongly give 3.
- Same height, rising widths. [[1,4],[2,4],[3,4]] gives 1; strict rise in height blocks it.
- One envelope. Always 1.
Common mistakes
- Sorting equal widths by height ascending, so envelopes of the same width chain together.
- Using
bisect_rightor≤, which lets equal heights extend a chain. - Returning
tailsor reading it as the chain; only its length is meaningful.
How to talk through it
- 1Clarify. Strictly smaller in both sides? No rotating? Can envelopes repeat?
- 2Give the DP. Sort by width;
dp[i]is the best chain ending at i. O(n²), too slow for 100,000. - 3Reduce to LIS. After sorting by width, a chain is a strictly increasing run of heights.
- 4Handle equal widths. Sort them tallest first so at most one can be picked; then run LIS with binary search.
- 5Test out loud. Run the same-width case and two identical envelopes before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?