354. Russian Doll Envelopes
Asked at 16Google53Amazon40Meta33Microsoft23Arcesium61Infosys30Verily93Media.net76UiPath64Zomato62Atlassian48Intuit43Flipkart43Goldman Sachs33TikTok26Uber22
Problem
envelopes[i] = [w, h]. One envelope fits inside another only if both its width and height are strictly smaller; you can't rotate them. Return the most envelopes you can nest one inside another.
Example: [[5,4],[6,4],[6,7],[2,3]] → 3 ([2,3] → [5,4] → [6,7])
Constraints: up to 10⁵ envelopes.
Sort by width ascending and height descending for equal widths (so two envelopes with the same width can't nest), then the answer is the LIS of heights in O(n log n).
[[5,4],[6,4],[6,7],[2,3]] -> sorted [2,3] [5,4] [6,7] [6,4]
heights 3 4 7 4 -> LIS 3,4,7 = 3
Complexity: O(n log n).
class Solution:
def maxEnvelopes(self, envelopes: List[List[int]]) -> int:
envelopes.sort(key=lambda e: (e[0], -e[1]))
tails = []
for _, h in envelopes:
i = bisect.bisect_left(tails, h)
if i == len(tails):
tails.append(h)
else:
tails[i] = h
return len(tails)
assert Solution().maxEnvelopes([[5, 4], [6, 4], [6, 7], [2, 3]]) == 3
assert Solution().maxEnvelopes([[1, 1], [1, 1], [1, 1]]) == 1
class Solution {
public int maxEnvelopes(int[][] envelopes) {
Arrays.sort(envelopes, (a, b) -> a[0] != b[0] ? a[0] - b[0] : b[1] - a[1]);
int[] tails = new int[envelopes.length];
int len = 0;
for (int[] e : envelopes) {
int i = Arrays.binarySearch(tails, 0, len, e[1]);
if (i < 0) i = -i - 1;
tails[i] = e[1];
if (i == len) len++;
}
return len;
}
}
func maxEnvelopes(envelopes [][]int) int {
sort.Slice(envelopes, func(i, j int) bool { // width up, and height down within a width
a, b := envelopes[i], envelopes[j]
return a[0] < b[0] || a[0] == b[0] && a[1] > b[1]
})
tails := []int{} // then LIS on heights
for _, e := range envelopes {
i := sort.SearchInts(tails, e[1])
if i == len(tails) {
tails = append(tails, e[1])
} else {
tails[i] = e[1]
}
}
return len(tails)
}