Russian Doll Envelopes

Sort by width ascending, height descending; then longest-increasing-subsequence on heights.

Hard
Time O(n log n) Space O(n)
LeetCode
3 min read
sorting lis binary-search

Problem#

An envelope (w, h) fits inside another (W, H) only if w < W and h < H. Find the maximum number of envelopes you can nest.

Examples#

  • [[5,4],[6,4],[6,7],[2,3]]3 (2,3 → 5,4 → 6,7)
  • [[1,1],[1,1],[1,1]]1

Constraints#

  • 1 <= envelopes.length <= 10^5, 1 <= w, h <= 10^5.

Approach#

Sort by width ascending; on ties, sort height descending so equal-width envelopes don’t form a “chain” via height. Then the answer is LIS over the heights, computable in O(n log n) with a patience-sorting tails array.

Solution#

Russian Doll Envelopes
class Solution {
public:
int maxEnvelopes(vector<vector<int>>& env) {
sort(env.begin(), env.end(), [](auto& a, auto& 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 tails.size();
}
};

Editorial#

The height-descending tie-breaker is the trick: if widths tie, we must not count multiple of them in the LIS, and descending heights guarantee that since LIS is strictly increasing. The tails array stores the smallest possible tail height per LIS length.

Complexity#

  • Time: O(n log n).
  • Space: O(n).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.