Russian Doll Envelopes - Problem

Imagine you have a collection of envelopes and you want to nest them inside each other like Russian dolls! 🎎

You are given a 2D array envelopes where envelopes[i] = [width, height] represents the dimensions of each envelope. An envelope can fit inside another envelope if and only if both its width and height are strictly smaller than the outer envelope.

Your goal: Find the maximum number of envelopes you can nest inside each other. Note that you cannot rotate the envelopes - they must maintain their original orientation.

Example: Given envelopes [[5,4],[6,4],[6,7],[2,3]], you can nest them as: [2,3] β†’ [5,4] β†’ [6,7] for a maximum of 3 envelopes.

Input & Output

example_1.py β€” Basic Case
$ Input: envelopes = [[5,4],[6,4],[6,7],[2,3]]
β€Ί Output: 3
πŸ’‘ Note: The maximum number of envelopes you can Russian doll is 3: [2,3] β†’ [5,4] β†’ [6,7]. Note that [6,4] cannot be used because it has the same width as [6,7].
example_2.py β€” Single Envelope
$ Input: envelopes = [[1,1]]
β€Ί Output: 1
πŸ’‘ Note: With only one envelope, the maximum nesting is 1 (the envelope itself).
example_3.py β€” No Nesting Possible
$ Input: envelopes = [[4,5],[4,6],[6,7],[2,3],[1,1]]
β€Ί Output: 4
πŸ’‘ Note: The optimal nesting is [1,1] β†’ [2,3] β†’ [4,5] β†’ [6,7] for a maximum of 4 envelopes.

Visualization

Tap to expand
[2,3][5,4][6,7]Maximum Nesting: 3 envelopesSorting Strategy:1. Width ascending: 2 < 5 < 6 = 62. Height descending for same width: 7 > 4Result: [2,3] β†’ [5,4] β†’ [6,7] β†’ [6,4]LIS on Heights [3,4,7,4]:Binary search finds LIS length = 3Algorithm Visualization3474Heights: [3,4,7,4] β†’ LIS length: 3Time Complexity: O(n log n)
Understanding the Visualization
1
Start with Unsorted Envelopes
Given envelopes with different dimensions [[5,4],[6,4],[6,7],[2,3]]
2
Smart Sorting Strategy
Sort by width↑, height↓ for same width: [[2,3],[5,4],[6,7],[6,4]]
3
Extract Heights for LIS
Create 1D problem: heights = [3,4,7,4], find LIS
4
Binary Search Optimization
Use binary search to efficiently build LIS: length = 3
Key Takeaway
🎯 Key Insight: Transform the 2D envelope problem into 1D Longest Increasing Subsequence by sorting smartly, then use binary search for optimal O(n log n) performance!

Time & Space Complexity

Time Complexity
⏱️
O(n log n)

O(n log n) for sorting + O(n log n) for LIS with binary search

n
2n
⚑ Linearithmic
Space Complexity
O(n)

Array to store the LIS sequence

n
2n
⚑ Linearithmic Space

Constraints

  • 1 ≀ envelopes.length ≀ 105
  • envelopes[i].length == 2
  • 1 ≀ widthi, heighti ≀ 105
  • Cannot rotate envelopes - must maintain original orientation
Asked in
Google 42 Amazon 38 Facebook 29 Microsoft 25 Apple 18
82.5K Views
Medium-High Frequency
~25 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
πŸ’‘ Explanation
AI Ready
πŸ’‘ Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen