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 INPUT 2D Array of Envelopes [w, h] [5, 4] w=5, h=4 [6, 4] w=6, h=4 [6, 7] w=6, h=7 [2, 3] w=2, h=3 envelopes = [[5,4], [6,4],[6,7],[2,3]] 4 envelopes total ALGORITHM STEPS 1 Sort by Width ASC If width equal, height DESC [2,3] [5,4] [6,7] [6,4] 2 Extract Heights heights = [3, 4, 7, 4] 3 Find LIS on Heights Longest Increasing Subseq 3 --> 4 --> 7 (4 skip) LIS = [3, 4, 7] length = 3 4 Binary Search Opt O(n log n) complexity Use patience sorting FINAL RESULT Maximum Nesting Chain [6, 7] [5, 4] [2, 3] [2,3] fits in [5,4] [5,4] fits in [6,7] Output: 3 Max dolls = 3 OK - Solution verified Key Insight: Sort envelopes by width ascending. When widths are equal, sort by height descending. This prevents selecting two envelopes with same width. Then find LIS on heights array. The 2D nesting problem reduces to 1D LIS problem solvable in O(n log n) using binary search. TutorialsPoint - Russian Doll Envelopes | Optimal Solution O(n log n)
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