Russian Doll Envelopes (LeetCode 354): Solution and Explanation
Each envelope has a width and a height, and one fits inside another only when both dimensions are strictly smaller. Find the largest number of envelopes you can nest inside one another, like a set of Russian dolls.
Watch it run step by step
Try your own input and write the code →Intuition
With one dimension this would be easy: sort and count distinct sizes. With two, the problem becomes finding the longest chain where both width and height strictly increase. A direct DP sorts by width and, for each envelope, looks back at every smaller one, which is the O(n²) longest increasing subsequence. The constraints allow up to 10^5 envelopes, so we need the O(n log n) version.
Sorting by width turns the problem into a one-dimensional LIS on heights, as long as we can guarantee that two envelopes with the same width never both end up in the chain. That is where the clever sort comes in. Within the same width, sort heights in descending order. A strictly increasing subsequence can never pick two items from a descending run, so equal widths are automatically excluded, while different widths are already in increasing order.
Once heights are lined up, use the patience sorting form of LIS. Keep an array lis where lis[i] is the smallest possible tail of an increasing subsequence of length i + 1. Each new height either extends the longest subsequence or replaces the first tail that is greater than or equal to it, found with binary search. The length of lis at the end is the answer.
It is worth convincing yourself why the replacement step is safe. Overwriting lis[pos] with a smaller height does not change how many envelopes we have nested so far; it just records that a chain of length pos + 1 can now end on a smaller envelope. Any later envelope that could extend the old chain can also extend the new one, so we only ever gain options.
Approach: Sort plus binary search LIS
- Sort envelopes by width ascending and, for equal widths, by height descending, using the key
(w, -h). - Extract the heights into a list in that order.
- For each height
h, findpos = bisect_left(lis, h), the first tail that is at leasth. - If
pos == len(lis), appendh, extending the longest chain by one. - Otherwise overwrite
lis[pos] = h, keeping a smaller tail for chains of that length. - Return
len(lis).
Step-by-step example
envelopes = [[5,4], [6,4], [6,7], [2,3]]
- Sorting by (width, -height) gives [[2,3], [5,4], [6,7], [6,4]], so the heights are [3, 4, 7, 4].
- Height 3:
lisis empty, so append.lis = [3]. - Height 4: it is larger than every tail, so append.
lis = [3, 4]. - Height 7: append again.
lis = [3, 4, 7]. - Height 4 (from [6,4]):
bisect_leftreturns 1, solis[1] = 4and the array stays [3, 4, 7]. The descending order stopped [6,4] from stacking on [6,7]. - The answer is 3: [2,3] inside [5,4] inside [6,7].
Code: Python, Java, C++
1class Solution:
2 def maxEnvelopes(self, envelopes: List[List[int]]) -> int:
3 # Sort by width ascending, height descending
4 envelopes.sort(key=lambda x: (x[0], -x[1]))
5
6 # Find LIS on heights using binary search
7 heights = [e[1] for e in envelopes]
8 lis = []
9
10 for h in heights:
11 pos = bisect_left(lis, h)
12 if pos == len(lis):
13 lis.append(h)
14 else:
15 lis[pos] = h
16
17 return len(lis)1class Solution {
2 public int maxEnvelopes(int[][] envelopes) {
3 // Sort by width ascending, height descending
4 Arrays.sort(envelopes, (a, b) -> a[0] != b[0] ? a[0] - b[0] : b[1] - a[1]);
5
6 // Find LIS on heights using binary search
7 List<Integer> lis = new ArrayList<>();
8
9 for (int[] env : envelopes) {
10 int h = env[1];
11 int pos = Collections.binarySearch(lis, h);
12 if (pos < 0) pos = -(pos + 1);
13 if (pos == lis.size()) {
14 lis.add(h);
15 } else {
16 lis.set(pos, h);
17 }
18 }
19
20 return lis.size();
21 }
22}1class Solution {
2public:
3 int maxEnvelopes(vector<vector<int>>& envelopes) {
4 // Sort by width ascending, height descending
5 sort(envelopes.begin(), envelopes.end(), [](auto& a, auto& b) {
6 return a[0] != b[0] ? a[0] < b[0] : a[1] > b[1];
7 });
8
9 // Find LIS on heights using binary search
10 vector<int> lis;
11
12 for (auto& env : envelopes) {
13 int h = env[1];
14 auto it = lower_bound(lis.begin(), lis.end(), h);
15 if (it == lis.end()) {
16 lis.push_back(h);
17 } else {
18 *it = h;
19 }
20 }
21
22 return lis.size();
23 }
24};Time and space complexity
O(n log n)
Sorting costs O(n log n), and each of the n heights does one binary search over lis, which costs O(log n).
O(n)
The heights list and the lis array each hold up to n values.
Other approaches
Quadratic DP (time O(n²), space O(n))
Sort by width, then let dp[i] be the longest chain ending at envelope i, computed from every j before it with strictly smaller width and height. It is easier to explain but too slow for the largest inputs.
Common mistakes
- Sorting heights ascending for equal widths, which lets [6,4] and [6,7] chain together even though their widths are equal.
- Using
bisect_rightinstead ofbisect_left, which allows equal heights to extend the sequence and breaks the strict inequality. - Treating
lisas the actual chain. It only stores smallest tails, so its contents may not form a real nesting, only its length is meaningful. - Running the O(n²) DP on 10^5 envelopes, which exceeds the time limit.
Frequently asked questions
Why sort height in descending order for the same width?
Envelopes of equal width cannot nest. Ordering their heights from tallest to shortest means a strictly increasing subsequence can pick at most one of them, so the LIS on heights respects the width rule without any extra checks.
How is Russian Doll Envelopes related to Longest Increasing Subsequence?
After the special sort, the answer is exactly the LIS of the height sequence. The problem is a two-dimensional LIS reduced to one dimension.
Why is the binary search LIS correct?
Keeping the smallest possible tail for each length never hurts, since a smaller tail leaves more room for later elements. The tails stay sorted, so binary search finds where each new value belongs.
Can envelopes be rotated in this problem?
No. Width must stay width and height must stay height. If rotation were allowed you would first normalize each envelope so that its smaller side is the width, and then the same sort and LIS approach would apply to the normalized pairs.