Russian Doll Envelopes - Problem

You are given a 2D array of integers envelopes where envelopes[i] = [wi, hi] represents the width and 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.

Input & Output

Example 1 — Basic Nesting
$ Input: envelopes = [[5,4],[6,4],[6,7],[2,3]]
Output: 3
💡 Note: Maximum nesting: [2,3] → [5,4] → [6,7]. Each envelope fits inside the next: (2<5 and 3<4), then (5<6 and 4<7).
Example 2 — Single Envelope
$ Input: envelopes = [[1,1]]
Output: 1
💡 Note: Only one envelope available, so maximum nesting is 1.
Example 3 — No Valid Nesting
$ Input: envelopes = [[4,5],[4,6],[6,7],[2,3],[1,1]]
Output: 3
💡 Note: Best nesting: [1,1] → [2,3] → [4,5] or [1,1] → [2,3] → [6,7]. Can't nest [4,5] and [4,6] together since widths are equal.

Constraints

  • 1 ≤ envelopes.length ≤ 105
  • envelopes[i].length == 2
  • 1 ≤ wi, hi ≤ 105

Visualization

Tap to expand
Russian Doll Envelopes: Maximum Nesting ProblemInput: [[5,4], [6,4], [6,7], [2,3]] → Output: 3Available Envelopes[2,3][5,4][6,4][6,7]Nesting Rules✓ [2,3] fits in [5,4]: 2 < 5 AND 3 < 4✓ [5,4] fits in [6,7]: 5 < 6 AND 4 < 7✗ [5,4] NOT in [6,4]: 4 = 4 (not <)Must be strictly smaller in BOTH dimensionsOptimal Nesting[2,3][5,4][6,7]Solution Strategy: Sort by width, then find longest increasing subsequence by heightMaximum envelopes that can be nested: 3Time Complexity: O(n log n) | Space Complexity: O(n)
Understanding the Visualization
1
Input Envelopes
Given envelopes with [width, height] dimensions
2
Valid Nesting
Envelope A fits in B if both width and height are strictly smaller
3
Maximum Chain
Find longest possible nesting sequence
Key Takeaway
🎯 Key Insight: Sort by one dimension, then solve longest increasing subsequence on the other
Asked in
Google 25 Amazon 18 Microsoft 15 Facebook 12
125.0K Views
Medium Frequency
~35 min Avg. Time
3.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