SDE & MLE Prep

354. Russian Doll Envelopes

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)