Online store~40 min2s · 256 MBtarget O(n log n) time, O(n) spaceclassic twin: lc-354binary-search
A gift shop sells flat boxes. Each box has a width and a height, measured in millimetres, and boxes are never turned. A box fits inside another box only when both its width and its height are strictly smaller.
A window display stacks boxes inside one another, like a set of nested trays. The staff want to know the longest chain of boxes that can be nested in one stack.
Write longest_nest(boxes).
boxes[i] is [width, height]. The boxes come in any order.Input: boxes = [[5, 4], [6, 4], [6, 7], [2, 3]]
Output: 3The chain [2, 3], [5, 4], [6, 7] nests. The solution sorts the boxes by width, from the smallest, and by height from the tallest when widths are equal. The trace then keeps tails: the smallest height that ends a chain of each length so far.
| Box | Height | Where it goes in tails |
tails after |
|---|---|---|---|
| [2, 3] | 3 | position 0, the list is empty | [3] |
| [5, 4] | 4 | position 1, after 3 | [3, 4] |
| [6, 7] | 7 | position 2, after 4 | [3, 4, 7] |
| [6, 4] | 4 | position 1, it replaces 4 | [3, 4, 7] |
The list has 3 entries, so the longest chain has 3 boxes.
Input: boxes = [[3, 3], [3, 3]]
Output: 1Equal boxes do not fit inside each other.
Input: boxes = [[1, 5], [2, 5]]
Output: 1The widths differ but the heights are equal, so neither box fits in the other.
1 ≤ boxes.length ≤ 100,0001 ≤ width, height ≤ 10,000,000Comparing every pair of boxes costs about n × n / 2 = 5 × 10^9 steps for 100,000 boxes. That is far over the budget of about 10^8 a second. After sorting by width, the task is the longest strictly rising run of heights, which a search in a sorted list solves in n log n.