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?
- A. By h ascending within equal w, so that the LIS can extend through equal widths
- B. The tie order does not matter because the LIS on h is strict
- C. By h DESCENDING within equal w, so two boxes of the same width can never both appear in the increasing h-sequence
- 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
- Problem: union–find runs m = 10⁶ operations on n = 10⁶ elements. Version X uses union by rank AND path compression; version Y uses path…
- Problem: a ring of n stalls holds 1 (occupied) or 0 (free). In one swap you exchange any two stalls. Find the minimum swaps to bring all…
- Problem: a stream of n = 2·10⁵ latencies; after each arrival report the median of the last k = 10⁵ values (sliding window median), time…
- Problem: A scoreboard calls a reading a 'leader' if it is strictly greater than every reading to its right (the last reading is always a…
- Problem: Return the squares of a sorted array (values may be negative) in non-decreasing order in O(n), filling the result from the back…
- Problem: A wallet starts with a positive balance s and then applies the day's changes in order. Find the minimum s such that the running…