Distribute Elements Into Two Arrays II - Problem
You are given a 1-indexed array of integers nums of length n.
We define a function greaterCount such that greaterCount(arr, val) returns the number of elements in arr that are strictly greater than val.
You need to distribute all the elements of nums between two arrays arr1 and arr2 using n operations.
In the first operation, append nums[1] to arr1. In the second operation, append nums[2] to arr2.
Afterwards, in the ith operation:
- If
greaterCount(arr1, nums[i]) > greaterCount(arr2, nums[i]), appendnums[i]toarr1. - If
greaterCount(arr1, nums[i]) < greaterCount(arr2, nums[i]), appendnums[i]toarr2. - If
greaterCount(arr1, nums[i]) == greaterCount(arr2, nums[i]), appendnums[i]to the array with a lesser number of elements. - If there is still a tie, append
nums[i]toarr1.
The array result is formed by concatenating the arrays arr1 and arr2.
Return the integer array result.
Input & Output
Example 1 — Basic Distribution
$
Input:
nums = [2,1,3,3]
›
Output:
[2,3,1,3]
💡 Note:
Start: arr1=[2], arr2=[1]. For nums[2]=3: count1=1 (2>3? no), count2=0 (1>3? no), so 0<1, add to arr2. For nums[3]=3: count1=1, count2=1, tie goes to smaller array (arr1). Result: arr1=[2,3], arr2=[1,3] → [2,3,1,3]
Example 2 — Equal Counts
$
Input:
nums = [5,4,3,8]
›
Output:
[5,3,4,8]
💡 Note:
Start: arr1=[5], arr2=[4]. For nums[2]=3: count1=1 (5>3), count2=1 (4>3), equal counts and equal sizes, tie goes to arr1. For nums[3]=8: count1=0, count2=0, equal counts, arr1 smaller, add to arr1.
Example 3 — Minimum Size
$
Input:
nums = [1,2]
›
Output:
[1,2]
💡 Note:
Only two elements, first goes to arr1, second to arr2. Result is concatenation: [1,2]
Constraints
- 1 ≤ nums.length ≤ 105
- 1 ≤ nums[i] ≤ 109
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code