All problems
0908HardArrayBinary Indexed TreeSegment TreeSimulation

Splitting a Feed Across Two Trays

Tracked in this browser only
Write code

Trains the technique from

LeetCode 3072Distribute Elements Into Two Arrays II

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

Readings arrive in the order given by nums and are laid out on two trays. The first reading goes on tray one and the second on tray two.

Every later reading is placed by comparing the trays. Count how many readings already on tray one are strictly greater than the arriving reading, and likewise for tray two. The reading joins whichever tray has the larger count. When the counts are equal it joins the tray holding fewer readings, and when that is equal too it joins tray one.

Return tray one's readings in the order they were placed, followed by tray two's.

Examples

Example 1

Input
nums = [14, 9, 21, 6, 17, 3]
Output
[14, 21, 6, 17, 3, 9]

Tray one opens with 14 and tray two with 9. The 21 beats nothing on either tray, so the counts tie at zero and the trays are the same size, sending it to tray one. The 6 is beaten by both readings on tray one and by the one on tray two, so it joins tray one, and the rest follow the same rule.

Example 2

Input
nums = [1, 2, 3]
Output
[1, 3, 2]

Neither tray holds anything greater than 3, so the counts tie at zero and both trays hold one reading, which sends it to tray one.

Example 3

Input
nums = [3, 2, 1]
Output
[3, 1, 2]

Tray one's 3 beats the arriving 1 while tray two's 2 also beats it, so the counts tie at one apiece and the equal sizes send it to tray one.

Constraints

  • 3 <= nums.length <= 10^5
  • 1 <= nums[i] <= 10^9

The signature

The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def result_array(nums: list[int]) -> list[int]:
Java
public int[] resultArray(int[] nums)
September 7
Apply