Russian Doll Envelopes
Difficulty: Hard · Pattern: 1-D Dynamic Programming · LeetCode #354
Envelope [w, h] fits inside another if both its width and its height are strictly smaller. Return the maximum number of envelopes you can nest (one inside another, Russian-doll style).
Examples
text
[[5,4],[6,4],[6,7],[2,3]] → 3 ([2,3] ⊂ [5,4] ⊂ [6,7])
[[1,1],[1,1],[1,1]] → 1Hints
- Sort by width. Then it's the Longest Increasing Subsequence on heights, except that equal widths must not chain.
- The trick: for equal widths, sort heights in descending order, so at most one envelope per width can join an increasing run.
Approach
- Sort by
(w ascending, h descending). - Find the strict LIS of the heights with patience sorting:
tails[k]= the smallest tail of an increasing subsequence of length k+1. For each h, replacetails[lower_bound(h)]or append.
The descending tie-break is the whole problem. With ascending heights, [6,4] and [6,7] would look nestable even though their widths are equal. O(n log n).
Complexity
Time: O(n log n). Space: O(n).
Python solution
import bisect
def maxEnvelopes(envelopes):
envelopes = sorted(envelopes, key=lambda e: (e[0], -e[1]))
tails = []
for _, h in envelopes:
i = bisect.bisect_left(tails, h)
if i == len(tails):
tails.append(h)
else:
tails[i] = h
return len(tails)JavaScript solution
function maxEnvelopes(envelopes) {
const e = [...envelopes].sort((a, b) => a[0] - b[0] || b[1] - a[1]), tails = [];
for (const [, h] of e) {
let lo = 0, hi = tails.length;
while (lo < hi) { const m = (lo + hi) >> 1; if (tails[m] < h) lo = m + 1; else hi = m; }
tails[lo] = h;
}
return tails.length;
}