Russian Doll Envelopes
Hard
Topics
You are given a list grid of envelopes where grid[i] = [w, h] is the width and height of envelope i. One envelope fits inside another only if both its width and height are strictly greater. Return the maximum number of envelopes you can nest (Russian doll style).
Example 1
[width, height].Input: envelopes = [[5,4],[6,4],[6,7],[2,3]] Output: 3
Example 2
Input: envelopes = [[1,1],[1,1],[1,1]] Output: 1
Constraints
- 1 <= grid.length <= 10^5
- grid[i].length == 2
- 1 <= w, h <= 10^5
Editorial — intuition, approach, complexity and pitfalls
Intuition
Nesting needs both dimensions to grow strictly, which is what makes this harder than a plain longest-increasing-subsequence problem. The brute force is the LIS recurrence over pairs: for each envelope, look at every earlier envelope that fits inside it and take the best chain. That is O(n^2) and correct, and it is where to start.
The way to do better is to spend one dimension. Sort by width ascending. Now any valid nesting must appear left-to-right in the sorted order, so the width constraint is handled by the ordering itself and the only thing left to enforce is that heights increase. The problem collapses to a one-dimensional LIS over heights — and LIS has an O(n log n) solution.
Except there is a trap, and it is the entire reason this problem is rated Hard. Two envelopes of equal width cannot nest, no matter what their heights are. If we sort equal widths by ascending height, those two look like a valid increasing pair to the height-only LIS, and we would count them as nested.
The fix is a sort key, not extra logic: for equal widths, sort height descending. Then within a block of equal widths the heights are decreasing, so an increasing subsequence can never pick two of them. The illegal pairs are made unselectable by the ordering rather than filtered out later.
💡 LIS in O(n log n): keep an array tails where tails[k] is the smallest possible tail of an increasing subsequence of length k+1. For each value, binary search the first tail that is not smaller and overwrite it; if none exists, append. tails is not itself a valid subsequence — only its length is meaningful.
Approach
- Sort by
(width ascending, height descending). - Run the patience-style LIS over heights: for each height,
bisect_leftintotails, appending if it is larger than everything and overwriting that position otherwise. - Return
len(tails).
bisect_left rather than bisect_right is deliberate: it makes the subsequence strictly increasing, because an equal height finds its own position and overwrites rather than extending. Strictness is what the nesting rule demands.
Dry Run
envelopes = [[5,4],[6,4],[6,7],[2,3]], expected 3.
sorted by (width asc, height desc):
[[2,3], [5,4], [6,7], [6,4]]
^^^^^ ^^^^^ the two width-6 envelopes, heights descending
(2,3): bisect_left([],3) = 0 = len -> append tails=[3]
(5,4): bisect_left([3],4) = 1 = len -> append tails=[3,4]
(6,7): bisect_left([3,4],7) = 2 = len -> append tails=[3,4,7]
(6,4): bisect_left([3,4,7],4) = 1 -> overwrite tails[1]=4
tails=[3,4,7] (unchanged)
answer len(tails) = 3 -> [2,3] inside [5,4] inside [6,7]The last step is the one to watch. (6,4) arrives after (6,7) precisely because of the descending tie-break, and it lands on an existing position instead of extending the chain. Had the tie-break been ascending, (6,4) would have come first and (6,7) would then have appended after it, reporting 4 — counting two width-6 envelopes as nested, which is illegal.
Complexity
- Time — O(n log n): the sort dominates at O(n log n), and the LIS pass is n binary searches of O(log n) each, so also O(n log n). Against O(n^2) for the pairwise LIS recurrence, which at the constraint limit of 10^5 envelopes is 10^10 operations versus about 1.7 million.
- Space — O(n): the
tailsarray, which can grow to n when every envelope nests, plus whatever the sort needs — O(log n) of stack for an in-place sort in C++, O(n) for Timsort's merge buffer in Java and Python. The sorted copy of the input is another O(n) unless sorting in place.
Common Pitfalls
- Sorting
(width asc, height asc). This is the mistake the problem is built around: equal-width envelopes then form a fake increasing run.[[1,1],[1,2],[1,3]]returns 3 when the answer is 1. - Using
bisect_right, which permits equal heights and so allows non-strict nesting.[[1,1],[1,1],[2,2]]returns 3 instead of 2. Note it agrees withbisect_lefton plenty of inputs, including the worked example above, so this is another bug that survives casual testing. - Trying to run LIS on widths instead, or on both dimensions at once. One dimension has to be discharged by the sort; attempting both leaves you back at the O(n^2) recurrence.
- Reading
tailsas the answer sequence. Its contents are not a real subsequence — in the trace above,[3,4,7]happens to be one, but after an overwrite it generally is not. Only the length is meaningful. - Forgetting that the sort must come before anything else. Running LIS on the input order gives an unrelated answer.
- Assuming rotation is allowed. An envelope cannot be turned sideways here, so
(4,6)does not fit inside(5,7)by swapping — onlywidth < widthandheight < heightcounts.
Full Solution — all languages
class Solution:
def maxEnvelopes(self, grid):
import bisect
env = sorted(grid, key=lambda x: (x[0], -x[1]))
tails = []
for w, h in env:
i = bisect.bisect_left(tails, h)
if i == len(tails):
tails.append(h)
else:
tails[i] = h
return len(tails)import java.util.*;
class Solution {
public int maxEnvelopes(int[][] grid) {
int[][] env = grid.clone();
Arrays.sort(env, (a, b) -> a[0] != b[0] ? a[0] - b[0] : b[1] - a[1]);
int[] tails = new int[env.length];
int size = 0;
for (int[] e : env) {
int h = e[1];
int lo = 0, hi = size;
while (lo < hi) {
int mid = (lo + hi) >>> 1;
if (tails[mid] < h) lo = mid + 1;
else hi = mid;
}
tails[lo] = h;
if (lo == size) size++;
}
return size;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int maxEnvelopes(vector<vector<int>>& grid) {
vector<vector<int>> env = grid;
sort(env.begin(), env.end(), [](const vector<int>& a, const vector<int>& b) {
return a[0] != b[0] ? a[0] < b[0] : a[1] > b[1];
})
;
vector<int> tails;
for (auto& e : env) {
int h = e[1];
auto it = lower_bound(tails.begin(), tails.end(), h);
if (it == tails.end()) tails.push_back(h);
else *it = h;
}
return (int)tails.size();
}
};/**
* @param {number[][]} grid
* @return {number}
*/ var maxEnvelopes = function(grid) {
const env = grid.slice().sort((a, b) => a[0] - b[0] || b[1] - a[1]);
const tails = [];
for (const e of env) {
const h = e[1];
let lo = 0, hi = tails.length;
while (lo < hi) {
const mid = (lo + hi) >> 1;
if (tails[mid] < h) lo = mid + 1;
else hi = mid;
}
tails[lo] = h;
}
return tails.length;
};