Distribute Elements Into Two Arrays II
Real-world version: Splitting a Feed Across Two TraysThe 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.
def result_array(nums: list[int]) -> list[int]:public int[] resultArray(int[] nums)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 10 test cases: 10 passed
- Passed: 3 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's
More on the same topics
- Fruits Into Baskets IIReal-world version: Crates That Find No BinEasy
- Number of Longest Increasing SubsequenceReal-world version: Counting The Longest Rising Gauge RunsMedium
- Queue Reconstruction by HeightReal-world version: Rebuild the Photo LineMedium
- Block Placement QueriesReal-world version: Rail Panel Fit OrdersHard