DYNP-P6

Nesting boxes

Practice 6 of 9Dynamic programming10 tests

The problem

Each box is given as (width, height). A box fits inside another if its width and its height are both strictly smaller. Boxes cannot be turned. Return the largest number of boxes that can be put one inside the next, like a set of nesting dolls.

nest([(5, 4), (6, 4), (6, 7), (2, 3)])   # 3
# (2, 3) inside (5, 4) inside (6, 7)
nest([(3, 1), (3, 2), (3, 3)])           # 1

Limits

  • Up to 100,000 boxes, with sides from 1 to 1,000,000. Comparing every pair (O(n²), n times n steps) is too slow; aim for O(n log n). sorted and bisect are allowed.

Builds on DYNP-6 Longest increasing subsequence.

Continue on a laptop

Practice runs Python in the browser and needs a keyboard and a wider screen. Read the problem and open hints here, then write your solution on a laptop. Progress is saved per browser for now, so hints opened here stay on this device.

Need a hint?0 of 3 opened

  1. Hint 1Nudge
  2. Hint 2Approach Open hint 1 first
  3. Hint 3Pseudocode Open hint 2 first
  4. Worked solutionlast resort Opens after all 3 hints
Python waits for a wider screensolution.py

Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.

10 tests, not run yet
Test results
#TestResultReads · time
1The exampleNot run
2Same widthNot run
3Same heightNot run
4No boxesNot run
5One boxNot run
6Equal boxesNot run
7No turningNot run
8Ten in a chainNot run
9100,000 boxesNot run
10100,000 boxes that all nestNot run