Russian Doll Envelopes — LeetCode 354 Python Solution
- Problem
- #354
- Pattern
- Monotonic Stack
- Reading time
- 2 min
- Source
- leetcode.com
The problem
You are given a 2D array of integers envelopes where envelopes[i] = [wi, hi] 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.
Example
- 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]).
Python solution
class Solution:
def maxEnvelopes(self, envelopes: List[List[int]]) -> int:
envelopes.sort(key=lambda x: (x[0], -x[1]))
d = [envelopes[0][1]]
for _, h in envelopes[1:]:
if h > d[-1]:
d.append(h)
else:
idx = bisect_left(d, h)
d[idx] = h
return len(d)Complexity
| Measure | Complexity |
|---|---|
| Time | O(log n) or O(n log n) |
| Space | O(1) auxiliary |
Pattern: Monotonic Stack
Answer "what is the next greater element" for every position in one pass. LeetCode 354. Russian Doll Envelopes is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.
The monotonic stack guide has the Python template for the pattern and the 225 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 354. Russian Doll Envelopes?
- LeetCode 354. Russian Doll Envelopes is rated Hard on LeetCode.
- What topics does LeetCode 354. Russian Doll Envelopes cover?
- LeetCode 354. Russian Doll Envelopes is tagged Array, Binary Search, Dynamic Programming and Sorting on LeetCode.