Skip to content
BytePatterns

Nesting Envelopes

HardDynamic Programming#binary-search#patience-sorting#sorting~45m

Problem

Each envelope is given as [width, height]. One envelope fits inside another only when it is strictly narrower and strictly shorter; rotating is not allowed. Return the largest number of envelopes you can nest one inside the next. The list may hold up to 100,000 envelopes, so a quadratic comparison of every pair is too slow.

Examples

Input:  envelopes = [[4, 5], [4, 6], [6, 7], [2, 3], [1, 1]]
Output: 4
Why:    [1, 1] inside [2, 3] inside [4, 5] inside [6, 7]
Input:  envelopes = [[3, 3], [3, 3]]
Output: 1
Why:    identical envelopes cannot hold each other
Input:  envelopes = []
Output: 0
Why:    edge case, nothing to nest

Hints

0 / 3

Stuck on the idea rather than the code? LIS in O(n log n) covers it.