375. Distribute Elements Into Two Arrays II

HardBinary Search

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 `i`th operation: - If `greaterCount(arr1, nums[i]) > greaterCount(arr2, nums[i])`, append `nums[i]` to `arr1`. - If `greaterCount(arr1, nums[i]) < greaterCount(arr2, nums[i])`, append `nums[i]` to `arr2`. - If `greaterCount(arr1, nums[i]) == greaterCount(arr2, nums[i])`, append `nums[i]` to the array with a **lesser** number of elements. - If there is still a tie, append `nums[i]` to `arr1`. The array `result` is formed by concatenating the arrays `arr1` and `arr2`. Return the integer array `result`.

Examples

Input: [2,1,3,3]

Output: [2,3,1,3]

Explanation: arr1=[2,3], arr2=[1,3]; concatenating gives [2,3,1,3].

Constraints

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

Run checks all cases above. Submit evaluates all test cases.