#2974
Minimum Number Game
EasyArraySortingHeap (Priority Queue)SimulationSortingArray Manipulation
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n log n)Space O(n)
Instead of simulating the game step by step, we can sort the array first and then rearrange the elements based on the game rules. This is efficient because sorting allows us to easily access the minimum elements in the correct order.
⚙️
Algorithm
4 steps- 1Step 1: Sort the nums array in ascending order.
- 2Step 2: Create an empty array arr to store the results.
- 3Step 3: Iterate through the sorted array, taking elements in pairs: first take the second element (Bob's turn), then take the first element (Alice's turn), and append them to arr.
- 4Step 4: Return the resulting array arr.
solution.py7 lines
1def minNumberGame(nums):
2 nums.sort()
3 arr = []
4 for i in range(0, len(nums), 2):
5 arr.append(nums[i + 1])
6 arr.append(nums[i])
7 return arrℹ
Complexity note: The time complexity is O(n log n) due to the sorting step, while the space complexity is O(n) for storing the result array.
- 1Sorting the array simplifies the problem.
- 2Understanding the order of operations is crucial.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.