354. Russian Doll Envelopes
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem asks for the maximum number of envelopes we can nest inside one another, forming a "Russian doll" chain. An envelope A can fit into envelope B only if both the width and height of A are strictly smaller than B's width and height. This problem can be modeled as finding the longest path in a directed acyclic graph (DAG), where envelopes are nodes and a directed edge exists from A to B if A can fit into B. A naive dynamic programming approach to find the longest path would be O(N^2), which is too slow given the constraint N <= 10^5. The problem structure suggests a more efficient approach, likely related to the Longest Increasing Subsequence (LIS) problem.
Solution
Russian Doll Envelopes in Python
import bisect
class Solution:
def maxEnvelopes(self, envelopes: list[list[int]]) -> int:
if not envelopes:
return 0
# Sort envelopes: width ascending, height descending for same width.
# The tuple (x[0], -x[1]) provides a concise way to implement this custom sort.
envelopes.sort(key=lambda x: (x[0], -x[1]))
# Find the Longest Increasing Subsequence (LIS) on the heights.
# The `dp` list stores the smallest tail of all increasing subsequences with length i+1.
dp = []
for _, height in envelopes:
# `bisect_left` finds the insertion point for `height` in `dp` to maintain sorted order.
# It returns an index `idx` such that all `dp[j] < height` for `j < idx`
# and all `dp[k] >= height` for `k >= idx`.
idx = bisect.bisect_left(dp, height)
if idx == len(dp):
# If `height` is greater than all elements in dp, it extends the LIS.
dp.append(height)
else:
# Replace the element at `idx` with `height`. This helps to form a new LIS
# of the same length but with a smaller tail, which might lead to a longer LIS later.
dp[idx] = height
# The length of dp is the length of the LIS.
return len(dp)
Russian Doll Envelopes in Java
class Solution {
public int maxEnvelopes(int[][] envelopes) {
if (envelopes == null || envelopes.length == 0 || envelopes[0] == null || envelopes[0].length == 0) {
return 0;
}
// Sort envelopes: width ascending, height descending for same width.
// This transforms the problem into finding the LIS of the heights.
Arrays.sort(envelopes, (a, b) -> {
if (a[0] != b[0]) {
return a[0] - b[0]; // Sort by width ascending
} else {
return b[1] - a[1]; // Sort by height descending
}
});
// Find the Longest Increasing Subsequence (LIS) on the heights.
// The `dp` ArrayList stores the smallest tail of all increasing subsequences with length i+1.
ArrayList<Integer> dp = new ArrayList<>();
for (int[] envelope : envelopes) {
int height = envelope[1];
// Binary search to find the insertion point for `height`.
int index = Collections.binarySearch(dp, height);
// If `height` is not found, binarySearch returns (-(insertion point) - 1).
// The insertion point is where the key would be inserted into the list.
if (index < 0) {
index = -(index + 1);
}
if (index == dp.size()) {
// If `height` is greater than all elements in dp, it extends the LIS.
dp.add(height);
} else {
// Replace the element with `height`. This helps to form a new LIS
// of the same length but with a smaller tail, which might lead to a longer LIS later.
dp.set(index, height);
}
}
// The size of dp is the length of the LIS.
return dp.size();
}
}
Russian Doll Envelopes in C++
class Solution {
public:
int maxEnvelopes(vector<vector<int>>& envelopes) {
if (envelopes.empty()) {
return 0;
}
// Sort envelopes: width ascending, height descending for same width.
// This transforms the problem into finding the LIS of the heights.
sort(envelopes.begin(), envelopes.end(), [](const vector<int>& a, const vector<int>& b) {
if (a[0] != b[0]) {
return a[0] < b[0]; // Sort by width ascending
}
return a[1] > b[1]; // Sort by height descending
});
// Find the Longest Increasing Subsequence (LIS) on the heights.
// The `dp` vector stores the smallest tail of all increasing subsequences with length i+1.
vector<int> dp;
for (const auto& envelope : envelopes) {
int height = envelope[1];
// Find the first element in dp that is not less than `height`.
// This is equivalent to `bisect_left` in Python.
auto it = lower_bound(dp.begin(), dp.end(), height);
if (it == dp.end()) {
// If `height` is greater than all elements in dp, it extends the LIS.
dp.push_back(height);
} else {
// Replace the element with `height`. This helps to form a new LIS
// of the same length but with a smaller tail, which might lead to a longer LIS later.
*it = height;
}
}
// The size of dp is the length of the LIS.
return dp.size();
}
};
Russian Doll Envelopes in TypeScript
function maxEnvelopes(envelopes: number[][]): number {
if (!envelopes || envelopes.length === 0) {
return 0;
}
// Sort envelopes: width ascending, height descending for same width.
// This transforms the problem into finding the LIS of the heights.
envelopes.sort((a, b) => {
if (a[0] !== b[0]) {
return a[0] - b[0]; // Sort by width ascending
}
return b[1] - a[1]; // Sort by height descending
});
// Find the Longest Increasing Subsequence (LIS) on the heights.
// The `dp` array stores the smallest tail of all increasing subsequences with length i+1.
const dp: number[] = [];
for (const envelope of envelopes) {
const height = envelope[1];
// Binary search to find the insertion point (lower_bound).
let left = 0, right = dp.length;
while (left < right) {
const mid = left + Math.floor((right - left) / 2);
if (dp[mid] < height) {
left = mid + 1;
} else {
right = mid;
}
}
const idx = left;
if (idx === dp.length) {
// If `height` is greater than all elements in dp, it extends the LIS.
dp.push(height);
} else {
// Replace the element at `idx` with `height`. This helps to form a new LIS
// of the same length but with a smaller tail, which might lead to a longer LIS later.
dp[idx] = height;
}
}
// The length of dp is the length of the LIS.
return dp.length;
};
More Hard LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.