#354
Russian Doll Envelopes
HardArrayBinary SearchDynamic ProgrammingSortingDynamic ProgrammingBinary SearchSorting
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n log n)Space O(n)
The optimal solution involves sorting the envelopes and then applying a dynamic programming approach to find the longest increasing subsequence based on height. This is efficient because it reduces the problem to a well-known algorithm.
⚙️
Algorithm
3 steps- 1Step 1: Sort the envelopes by width in ascending order. If widths are the same, sort by height in descending order.
- 2Step 2: Extract the heights from the sorted envelopes.
- 3Step 3: Use a dynamic programming approach (or binary search) to find the length of the longest increasing subsequence of heights.
solution.py16 lines
1# Full working Python code
2import bisect
3
4def maxEnvelopes(envelopes):
5 envelopes.sort(key=lambda x: (x[0], -x[1]))
6 dp = []
7 for _, h in envelopes:
8 pos = bisect.bisect_left(dp, h)
9 if pos == len(dp):
10 dp.append(h)
11 else:
12 dp[pos] = h
13 return len(dp)
14
15# Example usage
16print(maxEnvelopes([[5,4],[6,4],[6,7],[2,3]]))ℹ
Complexity note: The sorting step takes O(n log n) time, and finding the longest increasing subsequence using binary search takes O(n log n) as well, leading to an overall complexity of O(n log n).
- 1Sorting envelopes by width and height helps in reducing the complexity of finding the longest increasing subsequence.
- 2Using binary search to maintain the longest increasing subsequence allows us to efficiently find the position to replace or append heights.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.