Find Maximum Envelope Nesting
Company: Google
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: hard
Interview Round: Technical Screen
Quick Answer: This question evaluates algorithmic problem-solving skills, particularly reasoning about multi-dimensional ordering, sequence optimization, and time-complexity analysis.
Constraints
- 0 <= len(envelopes) <= 100000
- 1 <= width, height <= 1000000000
- Envelopes cannot be rotated
- Envelope A can fit into envelope B only if A.width < B.width and A.height < B.height
Examples
Input: [[5, 4], [6, 4], [6, 7], [2, 3]]
Expected Output: 3
Explanation: A valid nesting is [2,3] -> [5,4] -> [6,7], so the maximum count is 3.
Input: []
Expected Output: 0
Explanation: With no envelopes, no nesting is possible.
Input: [[1, 1]]
Expected Output: 1
Explanation: A single envelope can form a nesting chain of length 1 by itself.
Input: [[4, 5], [4, 6], [6, 7], [2, 3], [1, 1]]
Expected Output: 4
Explanation: One optimal chain is [1,1] -> [2,3] -> [4,5] -> [6,7]. Envelopes [4,5] and [4,6] cannot nest because their widths are equal.
Input: [[2, 2], [2, 3], [2, 4]]
Expected Output: 1
Explanation: All envelopes have the same width, so none can fit into another. The maximum chain length is 1.
Input: [[5, 4], [6, 4], [6, 7], [2, 3], [7, 8], [7, 8]]
Expected Output: 4
Explanation: A longest valid chain is [2,3] -> [5,4] -> [6,7] -> [7,8]. The duplicate [7,8] does not increase the answer.
Hints
- If you sort by width in ascending order, be careful with envelopes that have the same width.
- After sorting correctly, the problem can be reduced to finding the length of a longest increasing subsequence on heights.