Data Structures & AlgorithmsVery hardProduct company OA

Problem: boxes (w, h) can nest when BOTH dimensions are strictly smaller. Find the longest nesting chain for n ≤ 2·10⁵. A candidate sorts by w ascending and then runs an O(n log n) strictly-increasing LIS on h. How must ties in w be ordered for this to be correct?

  1. A. By h ascending within equal w, so that the LIS can extend through equal widths
  2. B. The tie order does not matter because the LIS on h is strict
  3. C. By h DESCENDING within equal w, so two boxes of the same width can never both appear in the increasing h-sequence
  4. D. Ties must be removed first by keeping only the tallest box of each width, after which any order works

Correct answer: C. By h DESCENDING within equal w, so two boxes of the same width can never both appear in the increasing h-sequence

With h ascending, (3, 4) followed by (3, 5) is an increasing h pair, so the LIS would nest two boxes of equal width – wrong. Sorting equal widths by decreasing height makes their heights non-increasing, so a strictly increasing subsequence picks at most one per width. Keeping only the tallest box per width loses chains that need a shorter box of that width (e.g. (2, 1), (3, 2), (4, 3) with (3, 9) also present). Total O(n log n).

More Coding Interview Problems questions

Exams that ask this topic