Python coding

Longest chain of nesting boxes

Each box in boxes is [width, height]. A box fits inside another only when it is strictly smaller in both width and height, and boxes can't be rotated. Return the largest number of boxes you can nest one inside the next, like Russian dolls.

boxes has 0 to 10,000 boxes with sides from 1 to 100,000, possibly repeated. Aim for O(n log n) time.

Besides the tests, one large input (4,500 boxes) with a ~200 ms limit (scaled to your device's speed): brute force won't pass.

  • max_nested([[5,4],[6,4],[6,7],[2,3]]) → 3
  • max_nested([[1,2],[1,3],[1,4]]) → 1
  • max_nested([[3,1],[1,3],[2,2]]) → 1
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Sorted by width, a chain is a strictly increasing subsequence of heights. chain[i] = 1 + max(chain[j]) over smaller earlier boxes is correct, but compares every pair: O(n²).

Hint 2

Keep tails[k]: the lowest height that ends a chain of k + 1 boxes. It stays sorted, so bisect_left finds where each height goes: append it, or lower an end.

Hint 3

Equal widths can't nest. Sort them by height descending, so two boxes of the same width never land in one increasing run of heights.

Solution and why it works
pythonO(n log n) · O(n)
from bisect import bisect_left

def max_nested(boxes: list[list[int]]) -> int:
    order = sorted(boxes, key=lambda b: (b[0], -b[1]))   # same width: tallest first, so they never chain
    tails = []                           # tails[k]: lowest height that ends a chain of k + 1 boxes
    for _, h in order:
        k = bisect_left(tails, h)        # the first chain end that is not below h
        if k == len(tails):
            tails.append(h)              # h extends the longest chain
        else:
            tails[k] = h                 # a lower end for chains of k + 1 boxes
    return len(tails)

Sorted by width, a chain is a strictly increasing subsequence of heights. tails[k], the lowest height that ends a chain of k + 1 boxes, stays sorted, so each box binary-searches its place: O(n log n) instead of comparing every pair. The trap is equal widths: with heights ascending, [1, 2], [1, 3], [1, 4] would chain 3 boxes that don't nest; heights descending within a width prevents it. bisect_left keeps heights strict, since equal heights don't nest either.

Related lab: Big-O growth