Advantage Shuffle - Problem

You are given two integer arrays nums1 and nums2 both of the same length. The advantage of nums1 with respect to nums2 is the number of indices i for which nums1[i] > nums2[i].

Return any permutation of nums1 that maximizes its advantage with respect to nums2.

Input & Output

Example 1 — Basic Advantage
$ Input: nums1 = [2,7,11,15], nums2 = [1,10,4,11]
Output: [2,11,7,15]
💡 Note: We rearrange nums1 to [2,11,7,15]. Comparing with nums2=[1,10,4,11]: 2>1 ✓, 11>10 ✓, 7>4 ✓, 15>11 ✓. All 4 positions give advantage.
Example 2 — Partial Advantage
$ Input: nums1 = [12,24,8,32], nums2 = [13,25,32,11]
Output: [24,32,8,12]
💡 Note: Optimal arrangement: 24>13 ✓, 32>25 ✓, 8≤32 ✗, 12>11 ✓. We get 3 advantages out of 4 possible.
Example 3 — Minimum Case
$ Input: nums1 = [3,5], nums2 = [6,4]
Output: [5,3]
💡 Note: With 2 elements: 5≤6 ✗, 3≤4 ✗. No advantage possible, but [5,3] is one valid arrangement.

Constraints

  • 1 ≤ nums1.length ≤ 105
  • nums2.length == nums1.length
  • 0 ≤ nums1[i], nums2[i] ≤ 109

Visualization

Tap to expand
Advantage Shuffle - Greedy with Sorting INPUT nums1: 2 7 11 15 nums2: 1 10 4 11 Goal: Maximize count of nums1[i] > nums2[i] Current advantages: i=0: 2 > 1 OK i=1: 7 < 10 X i=2: 11 > 4 OK i=3: 15 > 11 OK Advantage = 3 ALGORITHM STEPS 1 Sort nums1 [2, 7, 11, 15] 2 Sort nums2 with indices [(1,0),(4,2),(10,1),(11,3)] 3 Greedy Assignment Match smallest winner to each nums2 Best nums1 Result 1 (idx 0) 2 (smallest) res[0]=2 4 (idx 2) 7 (next) res[2]=7 10 (idx 1) 11 (next) res[1]=11 11 (idx 3) 15 (next) res[3]=15 4 Build result array Place in original positions FINAL RESULT Output: 2 11 7 15 Verification: i=0: 2 > 1 OK i=1: 11 > 10 OK i=2: 7 > 4 OK i=3: 15 > 11 OK Maximum Advantage = 4 (All win!) Time: O(n log n) Space: O(n) Key Insight: Use a greedy approach: for each element in nums2 (sorted), assign the smallest element from nums1 that can beat it. This ensures we don't waste larger nums1 values on smaller nums2 values. If no element can beat it, assign the smallest remaining (sacrifice the weakest). TutorialsPoint - Advantage Shuffle | Greedy with Sorting Approach
Asked in
Google 25 Amazon 18 Microsoft 15 Apple 12
89.2K Views
Medium Frequency
~25 min Avg. Time
1.5K 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