Want Help Cracking FAANG?

(Then click this)

×
Back to Question Bank

453. Minimum Moves to Equal Array Elements - Leetcode Solution

Problem Description

The "Minimum Moves to Equal Array Elements" problem asks you to determine the minimum number of moves required to make all the elements in an integer array nums equal. In one move, you can increment n - 1 elements by 1, where n is the length of the array. The operation can be repeated as many times as needed.

  • Each move must increment all elements except one (you choose which one to leave out).
  • There is always a valid solution.
  • The goal is to compute the minimum number of such moves needed so that all elements in nums are the same.

Example:
Input: nums = [1,2,3]
Output: 3

Thought Process

At first glance, you might think about incrementing the smallest elements until all match the largest, or performing the operation on random elements until equality is reached. However, simulating each move can quickly become inefficient, especially for large arrays.

A key observation is that incrementing n - 1 elements by 1 is equivalent to decrementing one element by 1 (since the relative difference between elements remains the same). This symmetry means that instead of thinking about increasing all but one, we can think about reducing one element at a time until all elements match the minimum value in the array.

The brute-force approach would be to simulate each move, but with this insight, we can look for a direct formula or shortcut.

Solution Approach

Let's break down the optimized solution step by step:

  1. Find the minimum value:
    • Since every move can be thought of as reducing one element by 1, the smallest possible value all numbers can reach is the current minimum in the array.
  2. Calculate total moves:
    • For each element in the array, calculate how much it needs to decrease to reach the minimum value.
    • Sum these differences for all elements.
  3. Return the result:
    • The sum is the minimum number of moves required to equalize the array.

Why does this work? Because each move reduces the gap between the largest and smallest elements by 1, and the total number of gaps to close is the sum of each element's difference from the minimum.

Example Walkthrough

Let's walk through the sample input: nums = [1, 2, 3]

  1. Find the minimum value:
    • Minimum is 1.
  2. Calculate differences:
    • For 1: 1 - 1 = 0
    • For 2: 2 - 1 = 1
    • For 3: 3 - 1 = 2
  3. Sum the differences:
    • 0 + 1 + 2 = 3
  4. Result:
    • It takes 3 moves to make all elements equal.

Step-by-step moves:

  • Start: [1, 2, 3]
  • Move 1: Increment first two elements: [2, 3, 3]
  • Move 2: Increment first and last: [3, 4, 4]
  • Move 3: Increment last two: [4, 5, 5]
  • But notice, after 3 moves, all can be made equal to 3 (if you always increment n-1 elements optimally).

Code Implementation

class Solution:
    def minMoves(self, nums):
        min_num = min(nums)
        return sum(num - min_num for num in nums)
      
class Solution {
public:
    int minMoves(vector<int>& nums) {
        int min_num = *min_element(nums.begin(), nums.end());
        int moves = 0;
        for (int num : nums) {
            moves += num - min_num;
        }
        return moves;
    }
};
      
class Solution {
    public int minMoves(int[] nums) {
        int min = Integer.MAX_VALUE;
        for (int num : nums) {
            if (num < min) min = num;
        }
        int moves = 0;
        for (int num : nums) {
            moves += num - min;
        }
        return moves;
    }
}
      
var minMoves = function(nums) {
    let minNum = Math.min(...nums);
    let moves = 0;
    for (let num of nums) {
        moves += num - minNum;
    }
    return moves;
};
      

Time and Space Complexity

Brute-force approach:

  • Each move simulates incrementing n - 1 elements, possibly up to the difference between max and min values.
  • Time complexity: O(max-min) * n in the worst case (very slow for large ranges).
  • Space complexity: O(1) extra space (in-place operations).
Optimized approach (as above):
  • Finding the minimum: O(n)
  • Summing differences: O(n)
  • Total time complexity: O(n)
  • Space complexity: O(1) (no extra data structures needed)

The optimized approach is highly efficient and suitable for large arrays.

Summary

The key insight in solving the "Minimum Moves to Equal Array Elements" problem is realizing that incrementing n - 1 elements is equivalent to decrementing one element, allowing us to shift our perspective. By summing the differences between each element and the minimum value, we can compute the answer in a single pass. This leads to a clear, concise, and efficient solution with linear time complexity, making it both elegant and practical for large inputs.