870. Advantage Shuffle LeetCode Solution
In this guide, you will get 870. Advantage Shuffle LeetCode Solution with the best time and space complexity. The solution to Advantage Shuffle problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.
Table of Contents
- Problem Statement
- Complexity Analysis
- Advantage Shuffle solution in C++
- Advantage Shuffle solution in Java
- Advantage Shuffle solution in Python
- Additional Resources

Problem Statement of Advantage Shuffle
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.
Example 1:
Input: nums1 = [2,7,11,15], nums2 = [1,10,4,11]
Output: [2,11,7,15]
Example 2:
Input: nums1 = [12,24,8,32], nums2 = [13,25,32,11]
Output: [24,32,8,12]
Constraints:
1 <= nums1.length <= 105
nums2.length == nums1.length
0 <= nums1[i], nums2[i] <= 109
Complexity Analysis
- Time Complexity: O(n\log n)
- Space Complexity: O(n)
870. Advantage Shuffle LeetCode Solution in C++
class Solution {
public:
vector<int> advantageCount(vector<int>& nums1, vector<int>& nums2) {
multiset<int> set{nums1.begin(), nums1.end()};
for (int i = 0; i < nums2.size(); ++i) {
const auto p =
*set.rbegin() <= nums2[i] ? set.begin() : set.upper_bound(nums2[i]);
nums1[i] = *p;
set.erase(p);
}
return nums1;
}
};
/* code provided by PROGIEZ */
870. Advantage Shuffle LeetCode Solution in Java
class Solution {
public int[] advantageCount(int[] nums1, int[] nums2) {
TreeMap<Integer, Integer> map = new TreeMap<>();
for (final int num : nums1)
map.merge(num, 1, Integer::sum);
for (int i = 0; i < nums2.length; i++) {
Integer key = map.higherKey(nums2[i]);
if (key == null)
key = map.firstKey();
if (map.merge(key, -1, Integer::sum) == 0)
map.remove(key);
nums1[i] = key;
}
return nums1;
}
}
// code provided by PROGIEZ
870. Advantage Shuffle LeetCode Solution in Python
from sortedcontainers import SortedList
class Solution:
def advantageCount(self, nums1: list[int], nums2: list[int]) -> list[int]:
sl = SortedList(nums1)
for i, num in enumerate(nums2):
index = 0 if sl[-1] <= num else sl.bisect_right(num)
nums1[i] = sl[index]
del sl[index]
return nums1
# code by PROGIEZ
Additional Resources
- Explore all LeetCode problem solutions at Progiez here
- Explore all problems on LeetCode website here
Happy Coding! Keep following PROGIEZ for more updates and solutions.