Show problems as
Classic problem #3072HardArrayBinary Indexed TreeSegment TreeSimulation

Distribute Elements Into Two Arrays II

Real-world version: Splitting a Feed Across Two Trays
Tracked in this browser only
Read Distribute Elements Into Two Arrays II on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

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 starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

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