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]), 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.

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
Distribute Elements: nums = [2,1,3,3]Input Array[2, 1, 3, 3]Initial: arr1=[2], arr2=[1]arr1: [2]Count > 3: 0arr2: [1]Count > 3: 0For nums[2]=3: Equal counts (0=0), equal sizes → add to arr1For nums[3]=3: Equal counts, arr2 smaller → add to arr2Final Result[2, 3, 1, 3]
Understanding the Visualization
1
Initialize
arr1 gets nums[0], arr2 gets nums[1]
2
Compare Counts
For each remaining element, count greater elements in both arrays
3
Distribute
Add to array with more greater elements, break ties by size
Key Takeaway
🎯 Key Insight: Use efficient data structures like Binary Indexed Trees to count greater elements in O(log n) time
Asked in
Google 15 Microsoft 12 Amazon 8
5.8K Views
Medium Frequency
~35 min Avg. Time
234 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen