#870
Advantage Shuffle
MediumArrayTwo PointersGreedySortingGreedySortingTwo Pointers
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n!) | O(n log n) |
| Space | O(n) | O(n) |
💡
Intuition
Time O(n log n)Space O(n)
The optimal solution uses sorting and a greedy approach. By sorting both arrays, we can efficiently match elements in nums1 to maximize the count of indices where nums1[i] > nums2[i]. This allows us to use a two-pointer technique to find the best matches.
⚙️
Algorithm
3 steps- 1Step 1: Sort nums1 and nums2 while keeping track of the original indices of nums2.
- 2Step 2: Use two pointers: one for nums1 and one for nums2.
- 3Step 3: For each element in nums1, if it can beat the current element in nums2, assign it and move both pointers. Otherwise, assign the smallest remaining element in nums1.
solution.py13 lines
1def advantageCount(nums1, nums2):
2 sorted_nums1 = sorted(nums1)
3 sorted_indices = sorted(range(len(nums2)), key=lambda i: nums2[i])
4 result = [0] * len(nums1)
5 j = 0
6 for num in sorted_nums1:
7 if num > nums2[sorted_indices[j]]:
8 result[sorted_indices[j]] = num
9 j += 1
10 else:
11 result[sorted_indices[-1]] = num
12 sorted_indices.pop()
13 return resultℹ
Complexity note: The time complexity is O(n log n) due to the sorting of nums1 and the indices. The space complexity is O(n) for storing the result and indices.
- 1Sorting helps in efficiently matching elements.
- 2Using indices allows us to keep track of original positions.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.