Tutorialspoint
Problem
Solution
Submissions

Russian Doll Envelopes

Certification: Advanced Level Accuracy: 0% Submissions: 0 Points: 15

Write a C++ program to solve the Russian Doll Envelopes problem. You are given a 2D array of integers `envelopes` where `envelopes[i] = [width_i, height_i]` represents the width and height of an envelope. One envelope can fit inside 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 nest inside each other.

Example 1
  • Input: envelopes = [[5,4],[6,4],[6,7],[2,3]]
  • Output: 3
  • Explanation:
    • The maximum number of nested envelopes is 3 ([2,3] => [5,4] => [6,7]).
Example 2
  • Input: envelopes = [[1,1],[1,1],[1,1]]
  • Output: 1
  • Explanation:
    • You cannot nest any envelope inside another since they all have the same dimensions.
Constraints
  • 1 ≤ envelopes.length ≤ 10^5
  • envelopes[i].length == 2
  • 1 ≤ width_i, height_i ≤ 10^5
  • Time Complexity: O(n log n)
  • Space Complexity: O(n)
Dynamic Programming AlgorithmsCapgeminiAdobe
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Sort the envelopes based on width (ascending) and if widths are equal, by height (descending)
  • After sorting, the problem transforms into finding the longest increasing subsequence based on heights
  • Use binary search to efficiently find the LIS
  • Be careful with envelopes that have equal width
  • Consider edge cases where no nesting is possible

Steps to solve by this approach:

 Step 1: Sort the envelopes by width in ascending order, and for envelopes with the same width, sort by height in descending order.
 Step 2: This special sorting ensures that we don't include multiple envelopes of the same width.
 Step 3: After sorting, the problem reduces to finding the Longest Increasing Subsequence (LIS) based on heights.
 Step 4: Use a dynamic array to keep track of the increasing sequence.
 Step 5: For each envelope, use binary search to find the correct position in our LIS array.
 Step 6: Replace the value at that position or append to the array if needed.
 Step 7: The length of the final array gives us the maximum number of nested envelopes.

Submitted Code :