Advantage Shuffle — LeetCode 870 Python Solution

MediumGreedyArrayTwo PointersSorting
Problem
#870
Reading time
3 min

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 ans

Complexity

MeasureComplexity
TimeO(n) (after optional sort O(n log n))
SpaceO(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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview