Python 2974.py
class Solution:
def numberGame(self, nums: List[int]) -> List[int]:
heapify(nums)
while nums:
alice = heappop(nums)
bob = heappop(nums)
yield bob
yield alice
Difficulty
and has an acceptance rate of about 86% (100k+ submissions).
AI Disclaimer
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.
Code Walkthrough
Overview
The provided implementation defines a class with a single method that transforms an input list of integers into a sequence of values produced by a generator. The method first arranges the numbers into a min-heap, then repeatedly extracts the two smallest elements, yielding them in a specific order. By using the heap data structure and a generator, the routine processes the data in a streaming fashion without allocating additional containers for the output.
Key Steps
The first operation converts the mutable list into a heap representation. This is achieved with a single call to the standard library routine that rearranges the list in-place.
heapify(nums)
After the heap is prepared, the method enters a loop that continues as long as the heap contains elements. Inside the loop the two smallest items are removed from the heap using the pop operation. The first pop retrieves the smallest element, which is stored in a temporary variable representing the first player's choice. The second pop obtains the next smallest element, representing the second player's choice.
while nums:
alice = heappop(nums)
bob = heappop(nums)
The generator then yields the second player's value followed by the first player's value. This ordering determines the final sequence that callers of the generator will observe.
yield bob
yield alice
Because the method uses yield, the caller receives each value as it is produced, allowing consumption of the sequence without materializing the entire result list.
Edge Cases
When the input list is empty, the initial heapification produces an empty heap and the loop condition fails immediately. In this situation the generator produces no values, which is a natural and safe outcome for an empty input. The algorithm also works correctly when the list contains an even number of elements; each iteration removes exactly two items, and the loop terminates precisely when the heap becomes empty. The ordering of the yields ensures that the second extracted element is always emitted before the first, preserving the intended alternation pattern.
Performance Optimizations
The use of heapify builds the heap in linear time, which is more efficient than inserting each element individually. Subsequent removals are performed with heappop, each taking logarithmic time relative to the current heap size, providing a balanced trade-off between extraction cost and overall throughput. By employing a generator (yield), the method avoids constructing an intermediate list of results, reducing memory pressure especially for large inputs. The lazy production of values also enables early termination by the caller if only a subset of the sequence is needed, further improving runtime efficiency.
ELI5 - Simplified Explanation
Imagine there is a big pile of numbered building blocks sitting on the floor. The code acts like a helper who looks at all those blocks and puts them in a special order so the smallest numbers are always right on top.
While there are still blocks left in the pile, the helper reaches out to grab the smallest one and calls it Alice. Then, the helper grabs the very next smallest one and calls it Bob. Even though Alice was picked up first, the helper shows Bob to everyone first, and then shows Alice right after. This happens over and over again, grabbing the two smallest blocks and swapping their order, until every single block has been picked up and shown.
Code Quality
Complexity Analysis
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
Other Solutions
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 | Java | C++ | Python | TS | ||||
| WalkCCC | Java | C++ | Python | ||||||
| leetcode.ca | Java | Go | C++ | Python | Rust | TS | |||
| Progiez | Java | C++ | Python | ||||||
| github | charles-wangkai | Java | |||||||
| everthis | JS | ||||||||
| fartem | Ruby | ||||||||
| fsq | C++ | ||||||||
| muhammadfarhankt | Go | ||||||||
| varunu28 | Java | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Python, Java | ||||||||
| leetcode.ca | C++, Go, Java, Python, Rust, TypeScript | ||||||||
| Progiez | C++, Java, Python | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JavaScript | ||||||||
| fartem | Ruby | ||||||||
| fsq | C++ | ||||||||
| muhammadfarhankt | Go | ||||||||
| varunu28 | Java |
Videos
Solved On The Same Day
- problem 1588: Sum of All Odd Length Subarrays
- problem 2325: Decode the Message
- problem 2367: Number of Arithmetic Triplets
- problem 2428: Maximum Sum of an Hourglass
Extra
- 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