π Problem Statement
You are given a list of envelopes with dimensions [width, height]
. One envelope can fit into another if both the width and height of one are strictly smaller than the other.
π§ Goal: Return the maximum number of envelopes you can nest (Russian doll style).
π₯ Example
python
Input: envelopes = [[5,4],[6,4],[6,7],[2,3]]
Output: 3
Explanation: The sequence [[2,3] => [5,4] => [6,7]] can be nested.
π§ Approach
This is a 2D version of Longest Increasing Subsequence (LIS).
π‘ Key Insight:
- Sort the envelopes:
- Ascending by width
- If widths are equal, descending by height
- Extract heights and run LIS on them.
Why sort heights in descending order when widths are equal?
To prevent envelopes with the same width from being nested.
π Python Code (Using Binary Search for LIS)
python
from bisect import bisect_left
class Solution:
def maxEnvelopes(self, envelopes: list[list[int]]) -> int:
# Step 1: Sort by width ASC, height DESC
envelopes.sort(key=lambda x: (x[0], -x[1]))
# Step 2: Extract the heights
heights = [h for w, h in envelopes]
# Step 3: Apply LIS on heights
lis = []
for h in heights:
idx = bisect_left(lis, h)
if idx == len(lis):
lis.append(h)
else:
lis[idx] = h
return len(lis)
π Step-by-Step Breakdown
- Sort envelopes:
[(2,3), (5,4), (6,7), (6,4)]
β sorted as [(2,3), (5,4), (6,7), (6,4)]
- Note that
(6,7)
comes before (6,4)
due to descending height for same width.
- Extract heights:
[3, 4, 7, 4]
- Apply LIS:
- 3 β [3]
- 4 β [3, 4]
- 7 β [3, 4, 7]
- 4 β replaces index 1 (4), remains [3, 4, 7]
β
Final length = 3
β±οΈ Time & Space Complexity
OperationComplexitySortingO(n log n)LIS (Binary Search)O(n log n)SpaceO(n)
π§΅ Alternate Approach (DP β Slower)
You can use classic DP with O(nΒ²) time, but it's inefficient for large inputs.
π§ Final Thoughts
This problem elegantly combines:
- Sorting tricks
- Dynamic programming (LIS)
- Binary search (via
bisect_left
)
Itβs an excellent real-world example of combining multiple algorithmic concepts. A must-practice for interview prep!