Problem 870

Abstract / Summary

Given two lists of equal length assign each element from the first list to an element in the second list to maximize the number of positions where the first list's value is greater while using each value once.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0870.py

class Solution:
    def advantageCount(self, nums1: List[int], nums2: List[int]) -> List[int]:
        # ascending order but keep original position
        n2 = sorted([ (n, i) for i, n in enumerate(nums2) ])
        order = [ i for n, i in n2 ]

        # min-heap
        heapify(nums1)

        result   = [ None ] * len(nums2)
        mismatch = []
        for i, o in n2:
            # find larger number in nums1
            while nums1 and i >= nums1[0]:
                mismatch.append(nums1[0])
                heappop(nums1)

            # use most suitable number, respect order
            if nums1:
                result[o] = heappop(nums1) # smallest number such that nums1 > nums2
            else:
                result[o] = mismatch.pop() # no advantage, pick any number from mismatch

        return result
24 lines | 851 bytes | submitted October 24, 2023 | GitHub   37% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 55% (100k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Greedy
  • Sorting
  • Two Pointers
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation solves the “advantage shuffle” problem: given two integer arrays nums1 and nums2 of equal length, it constructs a permutation of nums1 such that the number of positions where the element from nums1 is greater than the corresponding element from nums2 is maximized. The algorithm works by processing the elements of nums2 in ascending order while maintaining a min-heap of the available numbers from nums1. It carefully decides whether a larger number can be assigned to gain an advantage or whether a smaller number must be stored for later use.

Key Steps

Sorting nums2 while preserving original indices

The first operation creates a list of pairs (value, index) for each element of nums2 and sorts this list in ascending order of the values. The sorted list is stored in n2. The original positions are extracted into order, which is later used to place the chosen numbers back into the correct locations of the result array.

n2 = sorted([ (n, i) for i, n in enumerate(nums2) ])
order = [ i for n, i in n2 ]

Transforming nums1 into a min-heap

Instead of sorting nums1 repeatedly, the algorithm builds a min-heap from the entire list in a single step. This enables constant-time access to the smallest remaining element and logarithmic-time removal.

heapify(nums1)

Preparing the result container and a temporary storage for mismatched numbers

An output list result of the required length is allocated, initially filled with None. A secondary list mismatch is used to collect numbers from nums1 that cannot beat the current nums2 element.

result   = [ None ] * len(nums2)
mismatch = []

Iterating over the sorted nums2 elements

For each pair (i, o) taken from n2 (where i is the value from nums2 and o is its original index), the algorithm attempts to find a number in the heap that is strictly larger than i. It repeatedly removes the smallest heap element while it is not larger than i, appending those removed elements to mismatch. This loop guarantees that any number left in the heap is guaranteed to provide an advantage.

for i, o in n2:
    while nums1 and i >= nums1[0]:
        mismatch.append(nums1[0])
        heappop(nums1)

Selecting the appropriate number for the current position

If the heap still contains elements after the removal loop, the smallest element that is greater than i is popped and placed into the result at the original index o. If the heap is empty, meaning no remaining number can beat i, the algorithm falls back to the most recently stored mismatched number, which is taken from the end of mismatch. This ensures that every position receives a value, and the mismatched numbers are used only when an advantage is impossible.

    if nums1:
        result[o] = heappop(nums1)      # smallest number such that nums1 > nums2
    else:
        result[o] = mismatch.pop()      # no advantage, pick any number from mismatch

Returning the constructed permutation

After processing all elements, the fully populated result list is returned.

return result

Edge Cases Handled

When a value from nums2 is larger than or equal to every remaining element in the heap, the inner while loop exhausts the heap and moves all those smaller elements into mismatch. The subsequent if check detects the empty heap and retrieves a value from mismatch, guaranteeing that a number is still assigned even when no advantage is possible. This mechanism also gracefully handles the situation where nums1 is initially empty, as the loop will never enter and the fallback will immediately provide a value from mismatch. Additionally, because the algorithm processes nums2 in sorted order, it naturally accommodates duplicate values in either array without breaking the advantage logic.

Performance Optimizations

The conversion of nums1 into a min-heap via heapify runs in linear time, avoiding the overhead of repeatedly sorting or scanning the list. Access to the smallest element is constant-time, and removal (heappop) is logarithmic, which is efficient for the repeated extraction operations required by the algorithm. Sorting nums2 together with its indices provides a single ordered traversal that respects the original ordering constraints without additional data structures. The use of a simple Python list mismatch as a stack allows append and pop operations to execute in amortized constant time, making the fallback path fast when no advantageous number remains. These choices collectively keep the overall runtime low while maintaining clear and deterministic behavior.

written by openai gpt

ELI5 - Simplified Explanation

Imagine two teams of friends holding blocks with numbers on them. The goal is to see how many times a friend from the first team can hold a bigger number than a friend from the second team.

First, the friends in the second team stand in a line from the person with the smallest number to the person with the largest number. This helps look at the smallest challenges first.

Next, the friends in the first team put all their numbered blocks into a special pile that always keeps the smallest number right on top. This makes it really easy to grab the smallest block that is still big enough to win.

Now, everyone goes down the line one by one. For each person from the second team, the smallest block from the pile that is bigger than their number is chosen. If a block is too small to win, it is set aside in a leftover pile because it might be useful later.

If there is no block left that can win against a specific friend, a block is taken from the leftover pile and given to that friend instead. Since those blocks were already too small to win, it does not matter much which one they get. Every friend in the first team ends up with a spot in line that matches the person they were meant to play against.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 7 | μ = 6.88 | σ = 1.09

Complexity Analysis

Time: loglinear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java Rust Go TS
LeetcodeHelp C++ Python Java
Progiez C++ Python Java
github black-shadows C++
charles-wangkai Java
everthis JS
fpdjsns C++
fsq C++
halfrost Go
JoshCrozier JS
lkwq007 Python
ruoru Rust
suxrobGM C#
trung-hn Python
varunu28 Java
wisdompeak C++
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fpdjsns C++
fsq C++
halfrost Go
JoshCrozier JavaScript
lkwq007 Python
ruoru Rust
suxrobGM C#
trung-hn Python
varunu28 Java
wisdompeak C++
zfang399 C++
33 links | 19 authors | 8 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

1 easy 7 medium 1 hard
10 solutions   October 24, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality