Minimum Number Game — LeetCode 2974 Python Solution
- Problem
- #2974
- Pattern
- Heap / Priority Queue
- Reading time
- 2 min
- Source
- leetcode.com
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
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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n \times \log n) |
| Space | O(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.