Russian Doll Envelopes Problem
Description
LeetCode Problem 354.
You are given a 2D array of integers envelopes where envelopes[i] = [w_i, h_i] represents the width and the height of an envelope.
One envelope can fit into another if and only if both the width and height of one envelope are greater than the other envelope's width and height.
Return the maximum number of envelopes you can Russian doll (i.e., put one inside the other).
Note: You cannot rotate an envelope.
Example 1:
Input: envelopes = [[5,4],[6,4],[6,7],[2,3]]
Output: 3
Explanation: The maximum number of envelopes you can Russian doll is 3 ([2,3] => [5,4] => [6,7]).
Example 2:
Input: envelopes = [[1,1],[1,1],[1,1]]
Output: 1
Constraints:
1 <= envelopes.length <= 10^5envelopes[i].length == 21 <= w_i, h_i <= 10^5
Solution
Approach: Sort + Longest Increasing Subsequence
A chain of nested envelopes must be strictly increasing in both width and height. If we sort the envelopes by width, any chain becomes a subsequence of the sorted list. All that's left is to find the longest subsequence whose heights strictly increase, which is the classic longest increasing subsequence (LIS) problem.
Envelopes with the same width are the catch: they can't nest, but after sorting by width alone, an increasing run of heights could chain them together. To prevent that, sort equal widths by height in descending order. Then the heights inside a group of equal widths never increase, so the LIS takes at most one envelope from each group.
For the LIS itself, the O(n2) dynamic program is too slow for 105 envelopes. Use the greedy version with binary search instead. Keep an array tails, where tails[k] is the smallest height that can end an increasing chain of length k + 1. This array is always sorted. For each height h:
- find the first position with
tails[i] >= hby binary search, - if there is none,
hextends the longest chain, so append it; - otherwise set
tails[i] = h. A chain of that length can now end lower, which leaves more room for later envelopes.
Searching for >= h instead of > h keeps the chain strictly increasing: an equal height replaces a tail and never extends the chain. The answer is the length of tails.
Complexity: O(n log n) time for the sort and the binary searches. O(n) extra space.
from bisect import bisect_left
class Solution:
def maxEnvelopes(self, envelopes: List[List[int]]) -> int:
# width ascending; for equal widths, height descending so two of them never chain
envelopes.sort(key=lambda e: (e[0], -e[1]))
tails = [] # tails[k]: smallest last height of an increasing chain of length k + 1
for _, h in envelopes:
k = bisect_left(tails, h)
if k == len(tails):
tails.append(h)
else:
tails[k] = h
return len(tails)