Distribute Elements Into Two Arrays II - Problem
You're tasked with distributing elements from an array into two separate arrays using a greedy algorithm based on counting strategy!
Given a 1-indexed array nums, you need to distribute all elements between two arrays arr1 and arr2 following these rules:
- Operation 1: Add
nums[1]toarr1 - Operation 2: Add
nums[2]toarr2 - Operation i (i ≥ 3): Count elements strictly greater than
nums[i]in both arrays using functiongreaterCount(arr, val)
For each subsequent element, choose the array with:
- Higher count of elements greater than current element
- If counts are equal, choose array with fewer elements
- If still tied, choose
arr1
Example: If nums = [2,1,3,3]
- Step 1:
arr1 = [2],arr2 = [] - Step 2:
arr1 = [2],arr2 = [1] - Step 3: For
nums[3] = 3:greaterCount(arr1, 3) = 0,greaterCount(arr2, 3) = 0→ tie, butarr1andarr2same size → choosearr1 - Final: concatenate arrays to get result
Input & Output
example_1.py — Basic Distribution
$
Input:
[2,1,3,3]
›
Output:
[2,3,1,3]
💡 Note:
Step 1: arr1=[2], arr2=[]. Step 2: arr1=[2], arr2=[1]. Step 3: For 3, count1=0, count2=0, sizes equal → choose arr1. Step 4: For 3, count1=0, count2=0, arr1 has more elements → choose arr2.
example_2.py — Count-based Decision
$
Input:
[5,4,3,8]
›
Output:
[5,3,4,8]
💡 Note:
Step 1: arr1=[5], arr2=[]. Step 2: arr1=[5], arr2=[4]. Step 3: For 3, count1=1 (5>3), count2=1 (4>3), sizes equal → choose arr1. Step 4: For 8, count1=0, count2=0, arr2 smaller → choose arr2.
example_3.py — Single Element
$
Input:
[1]
›
Output:
[1]
💡 Note:
Only one element, goes directly to arr1. Final result is just [1].
Constraints
- 1 ≤ nums.length ≤ 105
- 1 ≤ nums[i] ≤ 109
- nums is 1-indexed in the problem statement
Visualization
Tap to expand
Understanding the Visualization
1
Initial Setup
Place first player in Team 1, second player in Team 2
2
Count Stronger Players
For each new player, count existing stronger players in each team
3
Make Decision
Join team with more stronger players, break ties by smaller team size
4
Optimize Counting
Use Binary Indexed Tree instead of linear counting for efficiency
Key Takeaway
🎯 Key Insight: Transform the O(n) counting problem into O(log n) range queries using Binary Indexed Trees, dramatically improving efficiency from O(n²) to O(n log n).
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code