Advantage Shuffle — LeetCode 870 Python Solution
MediumGreedyArrayTwo PointersSorting
- Problem
- #870
- Pattern
- Two Pointers
- Reading time
- 3 min
- Source
- leetcode.com
The 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].
Example
- Input
- nums1 = [2,7,11,15], nums2 = [1,10,4,11]
- Output
- [2,11,7,15]
Python solution
Python
class Solution:
def advantageCount(self, nums1: List[int], nums2: List[int]) -> List[int]:
nums1.sort()
t = sorted((v, i) for i, v in enumerate(nums2))
n = len(nums2)
ans = [0] * n
i, j = 0, n - 1
for v in nums1:
if v <= t[i][0]:
ans[t[j][1]] = v
j -= 1
else:
ans[t[i][1]] = v
i += 1
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) (after optional sort O(n log n)) |
| Space | O(1) auxiliary |
Pattern: Two Pointers
Use the order already in the input to discard half the search space at every step. LeetCode 870. Advantage Shuffle is filed here because LeetCode tags it Two Pointers, which is the vocabulary this hub collects.
The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 870. Advantage Shuffle?
- LeetCode 870. Advantage Shuffle is rated Medium on LeetCode.
- What is the time complexity of LeetCode 870. Advantage Shuffle?
- The Python solution on this page runs in O(n) (after optional sort O(n log n)).
- What is the space complexity of LeetCode 870. Advantage Shuffle?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 870. Advantage Shuffle cover?
- LeetCode 870. Advantage Shuffle is tagged Greedy, Array, Two Pointers and Sorting on LeetCode.