Minimum Number Game — LeetCode 2974 Python Solution

EasyArraySortingSimulationHeap (Priority Queue)
Problem
#2974
Reading time
2 min

The problem

You are given a 0-indexed integer array nums of even length and there is also an empty array arr. Alice and Bob decided to play a game where in every round Alice and Bob will do one move.

Example

Input
nums = [5,4,2,3]
Output
[3,2,5,4]
Explanation
In round one, first Alice removes 2 and then Bob removes 3. Then in arr firstly Bob appends 3 and then Alice appends 2. So arr = [3,2].

Python solution

Python
class Solution:
    def numberGame(self, nums: List[int]) -> List[int]:
        heapify(nums)
        ans = []
        while nums:
            a, b = heappop(nums), heappop(nums)
            ans.append(b)
            ans.append(a)
        return ans

Complexity

MeasureComplexity
TimeO(n \times \log n)
SpaceO(n) auxiliary

Pattern: Heap / Priority Queue

Keep only the best k elements, or always pull the smallest, in log time. LeetCode 2974. Minimum Number Game is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Heap (Priority Queue).

The heap / priority queue guide has the Python template for the pattern and the 163 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2974. Minimum Number Game?
LeetCode 2974. Minimum Number Game is rated Easy on LeetCode.
What is the time complexity of LeetCode 2974. Minimum Number Game?
The Python solution on this page runs in O(n \times \log n).
What is the space complexity of LeetCode 2974. Minimum Number Game?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 2974. Minimum Number Game cover?
LeetCode 2974. Minimum Number Game is tagged Array, Sorting, Simulation and Heap (Priority Queue) 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