AlgoMaster Logo

Russian Doll Envelopes

Ashish

Ashish Pratap Singh

hard

Problem Description

Solve it on LeetCode

Approaches

1. Dynamic Programming

Intuition:

The problem resembles the "Longest Increasing Subsequence" (LIS) problem. The main challenge is to properly define when one envelope can fit into another. An envelope (w1, h1) can fit into another envelope (w2, h2) if both w1 < w2 and h1 < h2.

Dynamic programming can be used by sorting the envelopes based on width, and then computing the LIS based on the height of envelopes such that previous envelopes' width and height are both less than the current one.

Steps:

  1. Sort the envelopes by width. If two envelopes have the same width, sort by height in descending order to avoid putting envelopes of the same width one inside the other.
  2. Use dynamic programming to find the longest increasing subsequence of heights.

Code:

2. Sort and Longest Increasing Subsequence (LIS)

Intuition:

Leverage the fact that when width is sorted, the problem simplifies to finding the LIS based on height. By sorting the second criteria (height) in descending order when widths are equal, we ensure no two envelopes of the same width contribute to the LIS.

Use a more optimal approach with a binary search to find the correct position of each height in the constructed LIS.

Steps:

  1. Sort envelopes based on width in ascending order, and height in descending order when widths are equal.
  2. Use the LIS approach with binary search to efficiently build the subsequence.

Code: