Ctrl K

Boxes Inside Boxes

Hard
A warehouse stores flat cardboard boxes. Box boxes[i] = [w, h] has width w and height h. One box fits inside another only if it is **strictly** smaller in both width and height. Boxes cannot be rotated: width stays width. You want to build a nested stack, a chain where each box sits inside the next one. Return the largest number of boxes such a chain can contain. Comparing all pairs in O(n²) is too slow here; aim for O(n log n).
Example 1
boxes=[[4, 9], [3, 2], [7, 10], [4, 5]] → 3

The chain [3, 2] → [4, 5] → [7, 10] works: each box is strictly smaller than the next in both width and height. Boxes [4, 5] and [4, 9] share a width, so they can never both be in a chain.

Example 2
boxes=[[2, 8], [5, 3], [9, 1]] → 1

The wider a box, the lower it is, so none fits into another. The answer is 1.

Example 3
boxes=[[6, 6], [6, 6]] → 1
Constraints
  • 1 ≤ len(boxes) ≤ 10⁵
  • boxes[i] is a pair [w, h]
  • 1 ≤ w, h ≤ 10⁵
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsStrict Climb From Spare Parts HardBest-Paying Set of Gigs HardThe Best-Paying Gigs HardClimbing Along Rows and Columns HardWords Hidden in a Text Medium
loading Python…
Input
boxes=[[4, 9], [3, 2], [7, 10], [4, 5]]
Expected
3

Run checks the first 3 tests in your browser. Submit checks all 99 tests on the server, hidden ones included.