Talentd
FleetCode
Make and follow sheets.Sign in

Minimum Number Game solution and explanation

EasyArrayHeap (Priority Queue)SimulationSorting5 min read85.5% acceptanceUpdated 9 Apr 2026
Leetcode | 2974. Minimum Number Game | Easy | Java SolutionDeveloper Docs · 7:03 · 1K viewsWatch on YouTube
9 more videos on this problem
  1. Leetcode | 2974. Minimum Number Game | Easy | Java SolutionDeveloper Docs · 7:03 · 1K views
  2. 2974 Minimum Number Game || Sorting + Swapping (For Beginners)Ayush Rao · 3:32 · 1K views
  3. 2974. Minimum Number Game (Leetcode Easy)Programming Live with Larry · 3:43 · 565 views
  4. LeetCode 2974 | Minimum Number Game | JavaSleepy Cracker · 4:19 · 298 views
  5. 43. Leetcode - 2974. Minimum Number Game : PriorityQueue (MinHeap)JavaCommunity · 5:57 · 177 views
  6. Leetcode 2974 Minimum Number GameAlgorithmicIQ · 9:04 · 160 views
  7. LeetCode 2974: Minimum Number GameSumedha Koranga · 7:32 · 129 views
  8. leetcode 2974 Minimum Number Game - swap neighbor elementsCode-Yao · 7:47 · 75 views
  9. LeetCode 2974 | Minimum Number Game 🎮 | Easy Java Solution | DSA Zero to HeroBindas Code · 8:42 · 55 views
  10. Day 112: LeetCode Problem 2974. Minimum Number Game - SwiftiOSxBank · 10:18 · 35 views

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. The rules of the game are as follows:

  • Every round, first Alice will remove the minimum element from nums, and then Bob does the same.
  • Now, first Bob will append the removed element in the array arr, and then Alice does the same.
  • The game continues until nums becomes empty.

Return the resulting array arr.

Example 1:

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].
At the begining of round two, nums = [5,4]. Now, first Alice removes 4 and then Bob removes 5. Then both append in arr which becomes [3,2,5,4].

Example 2:

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

Constraints:

  • 2 <= nums.length <= 100
  • 1 <= nums[i] <= 100
  • nums.length % 2 == 0

Approach overview

Problem Overview: You are given an integer array nums. In each step of the game, remove the two smallest numbers. Alice takes the smallest and Bob takes the second smallest, but Bob's number is placed in the result first followed by Alice's. Repeat until the array is empty and return the constructed sequence.

Approach 1: Simulate the Game Using Sorting (O(n log n) time, O(1) extra space)

The key observation: every round always selects the two smallest remaining numbers. If you sort the array first, those pairs naturally appear next to each other. After sorting in ascending order, iterate through the array with a step of two and swap each pair (nums[i], nums[i+1]). Append the second element first and the first element second to simulate Bob placing his number before Alice's. Sorting guarantees the pair represents the two smallest available values at that step. This approach is simple, reliable, and commonly expected in interviews when working with arrays and sorting.

Approach 2: Two Pointers Without Sorting (O(n²) time, O(1) space)

If sorting is not allowed, simulate the process directly. In each round, scan the remaining portion of the array to find the smallest and second smallest elements. Two indices track these candidates while iterating through the array. Once identified, append the second smallest value first (Bob) and then the smallest (Alice). Mark or move those elements so they are not used again. Because each round requires scanning the remaining numbers to locate two minimums, the total work grows quadratically. This approach demonstrates the raw simulation logic but is less efficient than sorting.

A variation sometimes discussed uses a heap (priority queue). Push all elements into a min-heap and pop twice each round. The first pop is Alice's number and the second is Bob's, but you append them in reverse order. That version runs in O(n log n) time similar to sorting but with additional heap overhead.

Recommended for interviews: The sorting-based simulation is the expected solution. It reduces the game mechanics to a simple observation: the smallest values will always be paired together. Showing the naive scanning approach first demonstrates understanding of the game rules, but the sorted pairing solution proves you can simplify the process and achieve O(n log n) efficiency.

Approach 1: Approach 1: Simulate the Game Using Sorting

This approach involves sorting the nums array first. By doing this, Alice always picks the current first (or minimum) element in the sorted array. Bob then picks the next minimum element, which is the next in order in the sorted version.

This simulation essentially involves maintaining pointers or indices to add elements accordingly to arr.

def min_number_game(nums):
    nums.sort()
    arr = []
    for i in range(0, len(nums), 2):
        arr.append(nums[i + 1])
        arr.append(nums[i])
    return arr

nums = [5, 4, 2, 3]
arr = min_number_game(nums)
print(arr)
import java.util.Arrays;

public class MinNumberGame {
    public static int[] minNumberGame(int[] nums) {
        Arrays.sort(nums);
        int[] arr = new int[nums.length];
        int index = 0;
        for (int i = 0; i < nums.length; i += 2) {
            arr[index++] = nums[i + 1];
            arr[index++] = nums[i];
        }
        return arr;
    }

    public static void main(String[] args) {
        int[] nums = {5, 4, 2, 3};
        int[] arr = minNumberGame(nums);
        for (int num : arr) {
            System.out.print(num + " ");
        }
    }
}
#include <iostream>
#include <vector>
#include <algorithm>

std::vector<int> minNumberGame(std::vector<int>& nums) {
    std::sort(nums.begin(), nums.end());
    std::vector<int> arr;
    for (int i = 0; i < nums.size(); i += 2) {
        arr.push_back(nums[i + 1]);
        arr.push_back(nums[i]);
    }
    return arr;
}

int main() {
    std::vector<int> nums = {5, 4, 2, 3};
    std::vector<int> arr = minNumberGame(nums);
    for (int num : arr) {
        std::cout << num << ' ';
    }
    return 0;
}
function minNumberGame(nums) {
    nums.sort((a, b) => a - b);
    let arr = [];
    for (let i = 0; i < nums.length; i += 2) {
        arr.push(nums[i + 1], nums[i]);
    }
    return arr;
}

const nums = [5, 4, 2, 3];
console.log(minNumberGame(nums));
#include <stdio.h>
#include <stdlib.h>

int compare(const void* a, const void* b) {
    return (*(int*)a - *(int*)b);
}

void minNumberGame(int* nums, int numsSize, int* arr) {
    qsort(nums, numsSize, sizeof(int), compare);
    int index = 0;
    for (int i = 0; i < numsSize; i += 2) {
        arr[index++] = nums[i + 1];
        arr[index++] = nums[i];
    }
}

int main() {
    int nums[] = {5, 4, 2, 3};
    int numsSize = 4;
    int arr[4];
    minNumberGame(nums, numsSize, arr);
    for (int i = 0; i < numsSize; i++) {
        printf("%d ", arr[i]);
    }
    return 0;
}
using System;
using System.Collections.Generic;

class MinNumberGame {
    static int[] MinGame(int[] nums) {
        Array.Sort(nums);
        int[] arr = new int[nums.Length];
        int index = 0;
        for (int i = 0; i < nums.Length; i += 2) {
            arr[index++] = nums[i + 1];
            arr[index++] = nums[i];
        }
        return arr;
    }

    static void Main() {
        int[] nums = {5, 4, 2, 3};
        int[] result = MinGame(nums);
        Console.WriteLine(string.Join(" ", result));
    }
}

We simply use Python's built-in sort to order nums. We then iterate and append the appropriate elements to the list arr, thereby simulating the game.

Complexity

Time complexity: O(n log n) for sorting.
Space complexity: O(n) due to storage in arr.

Try this approach in the editor

Approach 2: Approach 2: Two Pointers Without Sorting

This approach involves using two pointers to simulate the game without explicitly sorting the array. By repeatedly finding and removing the minimum two elements, it mimics the sorting behavior.

def min_number_game(nums):
    arr = [0] * len(nums)
    index = 0

    while index < len(nums):
        min1 = min2 = float('inf')
        min1_index = min2_index = -1

        for i in range(len(nums)):
            if nums[i] < min1:
                min2, min2_index = min1, min1_index
                min1, min1_index = nums[i], i
            elif nums[i] < min2:
                min2, min2_index = nums[i], i

        arr[index], arr[index+1] = min2, min1
        nums[min1_index], nums[min2_index] = float('inf'), float('inf')
        index += 2
    
    return arr

nums = [5, 4, 2, 3]
print(min_number_game(nums))
import java.util.Arrays;

public class MinNumberGame {
    public static int[] minNumberGame(int[] nums) {
        int[] arr = new int[nums.length];
        int index = 0;

        for (int i = 0; i < nums.length; i++) {
            arr[i] = nums[i];
        }
        
        while (index < nums.length) {
            int min1 = Integer.MAX_VALUE, min2 = Integer.MAX_VALUE;
            int min1_index = -1, min2_index = -1;

            for (int i = 0; i < nums.length; i++) {
                if (nums[i] < min1) {
                    min2 = min1;
                    min2_index = min1_index;
                    min1 = nums[i];
                    min1_index = i;
                } else if (nums[i] < min2) {
                    min2 = nums[i];
                    min2_index = i;
                }
            }

            arr[index++] = min2;
            arr[index++] = min1;

            nums[min1_index] = Integer.MAX_VALUE;
            nums[min2_index] = Integer.MAX_VALUE;
        }

        return arr;
    }

    public static void main(String[] args) {
        int[] nums = {5, 4, 2, 3};
        int[] arr = minNumberGame(nums);
        for (int num : arr) {
            System.out.print(num + " ");
        }
    }
}
#include <iostream>
#include <vector>
#include <climits>

std::vector<int> minNumberGame(std::vector<int>& nums) {
    std::vector<int> arr(nums.size());
    int index = 0;
    while (index < nums.size()) {
        int min1 = INT_MAX, min2 = INT_MAX;
        int min1_index = -1, min2_index = -1;

        for (int i = 0; i < nums.size(); i++) {
            if (nums[i] < min1) {
                min2 = min1;
                min2_index = min1_index;
                min1 = nums[i];
                min1_index = i;
            } else if (nums[i] < min2) {
                min2 = nums[i];
                min2_index = i;
            }
        }

        arr[index++] = min2;
        arr[index++] = min1;

        nums[min1_index] = INT_MAX;
        nums[min2_index] = INT_MAX;
    }
    return arr;
}

int main() {
    std::vector<int> nums = {5, 4, 2, 3};
    std::vector<int> arr = minNumberGame(nums);
    for (int num : arr) {
        std::cout << num << ' ';
    }
    return 0;
}
function minNumberGame(nums) {
    let arr = new Array(nums.length);
    let index = 0;

    while (index < nums.length) {
        let min1 = Infinity, min2 = Infinity;
        let min1_index = -1, min2_index = -1;

        for (let i = 0; i < nums.length; i++) {
            if (nums[i] < min1) {
                min2 = min1;
                min2_index = min1_index;
                min1 = nums[i];
                min1_index = i;
            } else if (nums[i] < min2) {
                min2 = nums[i];
                min2_index = i;
            }
        }

        arr[index++] = min2;
        arr[index++] = min1;

        nums[min1_index] = Infinity;
        nums[min2_index] = Infinity;
    }

    return arr;
}

let nums = [5, 4, 2, 3];
console.log(minNumberGame(nums));
#include <stdio.h>
#include <limits.h>

void minNumberGame(int* nums, int numsSize, int* arr) {
    int index = 0;
    while (index < numsSize) {
        int min1 = INT_MAX, min2 = INT_MAX;
        int min1_index = -1, min2_index = -1;

        for (int i = 0; i < numsSize; i++) {
            if (nums[i] < min1) {
                min2 = min1;
                min2_index = min1_index;
                min1 = nums[i];
                min1_index = i;
            } else if (nums[i] < min2) {
                min2 = nums[i];
                min2_index = i;
            }
        }

        arr[index++] = min2;
        arr[index++] = min1;

        nums[min1_index] = INT_MAX;
        nums[min2_index] = INT_MAX;
    }
}

int main() {
    int nums[] = {5, 4, 2, 3};
    int numsSize = 4;
    int arr[4];
    minNumberGame(nums, numsSize, arr);
    for (int i = 0; i < numsSize; i++) {
        printf("%d ", arr[i]);
    }
    return 0;
}
using System;

class MinNumberGame {
    static int[] MinGame(int[] nums) {
        int[] arr = new int[nums.Length];
        int index = 0;

        while (index < nums.Length) {
            int min1 = int.MaxValue, min2 = int.MaxValue;
            int min1_index = -1, min2_index = -1;

            for (int i = 0; i < nums.Length; i++) {
                if (nums[i] < min1) {
                    min2 = min1;
                    min2_index = min1_index;
                    min1 = nums[i];
                    min1_index = i;
                } else if (nums[i] < min2) {
                    min2 = nums[i];
                    min2_index = i;
                }
            }

            arr[index++] = min2;
            arr[index++] = min1;

            nums[min1_index] = int.MaxValue;
            nums[min2_index] = int.MaxValue;
        }
        return arr;
    }

    static void Main() {
        int[] nums = {5, 4, 2, 3};
        int[] result = MinGame(nums);
        Console.WriteLine(string.Join(" ", result));
    }
}

This Python function effectively finds the smallest unique pair in the list repeatedly, placing them in arr after selection.

Complexity

Time complexity: O(n^2) with each scan of the list.
Space complexity: O(1) in terms of external space usage.

Try this approach in the editor

Approach 3: Simulation + Priority Queue (Min Heap)

We can put the elements of the array nums into a min heap one by one. Each time, we take out two elements a and b from the min heap, and then sequentially put b and a into the answer array until the min heap is empty.

The time complexity is O(n times log n), and the space complexity is O(n). Here, n is the length of the array nums.

function numberGame(nums: number[]): number[] {
    const pq = new MinPriorityQueue<number>();
    for (const x of nums) {
        pq.enqueue(x);
    }
    const ans: number[] = [];
    while (pq.size()) {
        const a = pq.dequeue();
        const b = pq.dequeue();
        ans.push(b, a);
    }
    return ans;
}
func numberGame(nums []int) (ans []int) {
	pq := &hp{nums}
	heap.Init(pq)
	for pq.Len() > 0 {
		a := heap.Pop(pq).(int)
		b := heap.Pop(pq).(int)
		ans = append(ans, b)
		ans = append(ans, a)
	}
	return
}

type hp struct{ sort.IntSlice }

func (h *hp) Less(i, j int) bool { return h.IntSlice[i] < h.IntSlice[j] }
func (h *hp) Pop() interface{} {
	old := h.IntSlice
	n := len(old)
	x := old[n-1]
	h.IntSlice = old[0 : n-1]
	return x
}
func (h *hp) Push(x interface{}) {
	h.IntSlice = append(h.IntSlice, x.(int))
}
use std::cmp::Reverse;
use std::collections::BinaryHeap;

impl Solution {
    pub fn number_game(nums: Vec<i32>) -> Vec<i32> {
        let mut pq = BinaryHeap::new();

        for &x in &nums {
            pq.push(Reverse(x));
        }

        let mut ans = Vec::new();

        while let Some(Reverse(a)) = pq.pop() {
            if let Some(Reverse(b)) = pq.pop() {
                ans.push(b);
                ans.push(a);
            }
        }

        ans
    }
}
Try this approach in the editor

Approach 4: Sorting + Swapping

We can sort the array nums, and then iterate through the array, swapping adjacent elements each time until the iteration is complete, and return the swapped array.

The time complexity is O(n log n), and the space complexity is O(log n). Here, n is the length of the array nums.

function numberGame(nums: number[]): number[] {
    nums.sort((a, b) => a - b);
    for (let i = 0; i < nums.length; i += 2) {
        [nums[i], nums[i + 1]] = [nums[i + 1], nums[i]];
    }
    return nums;
}
func numberGame(nums []int) []int {
	sort.Ints(nums)
	for i := 0; i < len(nums); i += 2 {
		nums[i], nums[i+1] = nums[i+1], nums[i]
	}
	return nums
}
impl Solution {
    pub fn number_game(nums: Vec<i32>) -> Vec<i32> {
        let mut nums = nums;
        nums.sort_unstable();
        for i in (0..nums.len()).step_by(2) {
            nums.swap(i, i + 1);
        }
        nums
    }
}
Try this approach in the editor

Complexity comparison

ApproachComplexity
Approach 1: Simulate the Game Using Sorting

Time complexity: O(n log n) for sorting.
Space complexity: O(n) due to storage in arr.

Approach 2: Two Pointers Without Sorting

Time complexity: O(n^2) with each scan of the list.
Space complexity: O(1) in terms of external space usage.

Simulation + Priority Queue (Min Heap)–
Sorting + Swapping–

Complexity analysis

ApproachTimeSpaceWhen to Use
Simulate Using SortingO(n log n)O(1) extraBest general solution. Simple implementation after sorting the array.
Two Pointers Without SortingO(n²)O(1)Useful for understanding the raw simulation when sorting or extra structures are avoided.

Frequently asked questions

Is Minimum Number Game easy or hard?

Minimum Number Game is classified as Easy with a high acceptance rate around 85%. The main trick is recognizing that sorting automatically groups the smallest pairs, allowing the game simulation to be implemented with a simple swap loop.

How to solve Minimum Number Game in O(n)?

An O(n) solution is generally not feasible for arbitrary integers because you must repeatedly identify the two smallest elements. That operation typically requires sorting (O(n log n)) or a heap. Linear time would only be possible with special constraints such as small bounded values enabling counting sort.

Minimum Number Game Python or Java solution?

Most implementations sort the array and then iterate in steps of two, swapping each adjacent pair. The logic is identical across Python, Java, C++, and JavaScript: sort the array, then output [nums[i+1], nums[i]] for every pair.

What is the best approach for Minimum Number Game?

The most practical solution sorts the array first, then processes elements in pairs. After sorting, swap each adjacent pair so the second smallest number appears before the smallest. This directly simulates the game rule and runs in O(n log n) time with O(1) extra space.

What data structure is used in Minimum Number Game?

The common solution relies on arrays and sorting. Another valid approach uses a min-heap (priority queue) to repeatedly extract the two smallest numbers. Both methods ensure the smallest elements are processed first.

What is the time complexity of Minimum Number Game?

The optimal solution runs in O(n log n) time due to the sorting step. After sorting, constructing the result by swapping adjacent pairs takes O(n) time. Space complexity is O(1) if the result is built in the same array or O(n) if a new array is returned.

Is Minimum Number Game asked at Google, Amazon, or Meta?

Problems like Minimum Number Game appear in coding interviews at companies such as Amazon, Google, and Meta as easy warm-up questions. They test basic understanding of arrays, sorting, and simple simulation logic rather than complex algorithms.

Comments

Now write it yourselfClose this page and solve Minimum Number Game in the editor, without looking.
Practise Minimum Number Game