Taro Logo

Minimum Moves to Equal Array Elements

#87 Most AskedMedium
0 views
Topics:
Arrays

Given an integer array nums of size n, return the minimum number of moves required to make all array elements equal.

In one move, you can increment n - 1 elements of the array by 1.

Example 1:

Input: nums = [1,2,3]
Output: 3
Explanation: Only three moves are needed (remember each move increments two elements):
[1,2,3]  =>  [2,3,3]  =>  [3,4,3]  =>  [4,4,4]

Example 2:

Input: nums = [1,1,1]
Output: 0

Constraints:

  • n == nums.length
  • 1 <= nums.length <= 105
  • -109 <= nums[i] <= 109
  • The answer is guaranteed to fit in a 32-bit integer.

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the range of values for the elements inside the `nums` array, and can we expect negative numbers or zeros?
  2. What are the constraints on the size of the array `n`?
  3. How should we handle a trivial case where the array has only a single element, or where all elements are already equal?
  4. Is it guaranteed that a solution always exists within integer limits, or could the number of moves exceed the maximum value of a standard 32-bit integer?
  5. Since incrementing $n-1$ elements by 1 is mathematically equivalent to decrementing 1 element by 1, can we assume the problem requires reducing all elements down to the minimum element in the array?

Brute Force Solution

Approach

Imagine you have a group of items with different sizes, and you want to make them all exactly equal by adding tiny bits to them. The brute force strategy involves testing every single possible final target value, and for each one, calculating how much effort is needed to bring every single item up to that target.

Here's how the algorithm would work step-by-step:

  1. Pick a starting number as your goal for all the items.
  2. Go through every single item in your group and count how many steps it takes to increase that item until it matches your chosen goal.
  3. Add up all those individual steps to find the total effort required for that particular goal.
  4. Write down this total effort, and then completely reset and choose a different number to be your new goal.
  5. Repeat this process for every reasonable number you can think of as a potential final target.
  6. Compare the total efforts you recorded for all the different goals you tested.
  7. Select the goal that required the fewest total steps to make everything equal, and that gives you your final answer.

Code Implementation

def min_moves(nums):
    if not nums:
        return 0

    minimum_possible_target = min(nums)
    maximum_possible_target = max(nums) + len(nums)
    minimum_total_effort = float('inf')

    # We test every plausible final value as a goal to find the absolute minimum effort
    for current_target_goal in range(minimum_possible_target, maximum_possible_target):
        current_total_effort = 0

        for item_value in nums:
            current_total_effort += (current_target_goal - item_value)

        # We track the lowest effort encountered across all tested target goals
        if current_total_effort < minimum_total_effort:
            minimum_total_effort = current_total_effort

    # Returning the optimal effort ensures we meet the problem constraints using brute force
    return minimum_total_effort

Big(O) Analysis

Time Complexity
O(n²) – For each potential target value we choose to test, we iterate through all n items in the array to calculate the required steps. Assuming the range of possible target values is also proportional to the input size n, we repeat this full array scan approximately n times. This results in about n multiplied by n operations, which yields a total cost proportional to n squared. Therefore, simplifying the total operations formula of n * n gives a final Big O time complexity of O(n²).
Space Complexity
O(1) – The brute force strategy described only utilizes a few primitive integer variables to keep track of the chosen goal, the current item being processed, and the running total effort. No dynamic data structures, temporary lists, or recursive stack frames are created during the execution of the algorithm. Because the amount of auxiliary memory remains constant regardless of the input size N, the space complexity is strictly O(1).

Optimal Solution

Approach

Instead of trying to increase numbers to make them match, the clever trick is to realize that adding one to many numbers is the same as subtracting one from just the single smallest number. By shifting our perspective this way, we can figure out the total effort by simply measuring how far each item needs to drop to reach the level of the smallest one.

Here's how the algorithm would work step-by-step:

  1. Look at all the items and find the absolute smallest one.
  2. Imagine that instead of building the rest of the items up to match the highest ones, you are bringing everyone else down to meet this smallest baseline.
  3. Compare every single item against that smallest baseline to see how far apart they are.
  4. Add up all of those individual gaps to find the total amount of downward steps needed.
  5. That final sum is your answer, completely avoiding the need to simulate every single move one by one.

Code Implementation

def min_moves(array_elements):
    # Finding the absolute minimum is crucial because all elements will eventually be reduced to match this baseline value.
    smallest_baseline = min(array_elements)
    
    total_downward_steps = 0
    
    # Summing individual gaps avoids simulating every single move, drastically improving time complexity.
    for current_item in array_elements:
        total_downward_steps += current_item - smallest_baseline
        
    # The total accumulated downward steps directly equal the minimum moves required to equalize the array.
    return total_downward_steps

Big(O) Analysis

Time Complexity
O(n) – To find the minimum moves, we first iterate through all n elements of the array in a single pass to locate the absolute smallest baseline value. Next, we run a second pass over the same n elements to calculate the individual gap between each item and that minimum baseline. Summing these differences requires checking every item exactly once per pass without nested loops or recursion. This results in approximately 2n total operations, which simplifies to O(n).
Space Complexity
O(1) – The algorithm only requires a few primitive variables, such as a pointer to track the smallest baseline and an accumulator for the total gaps, regardless of the input size. Because no auxiliary data structures or recursive call stacks are created, the memory footprint remains constant. As the input size N grows, the extra memory used does not scale at all. Therefore, the auxiliary space complexity is O(1).

Edge Cases

Array with a single element
How to Handle:
The algorithm naturally computes zero moves since all elements are already equal and the sum of differences from the minimum is zero.
Array with all elements already equal
How to Handle:
The minimum value equals all other elements, resulting in a difference of zero for every element and a total move count of zero.
Array containing negative numbers and mixed signs
How to Handle:
Mathematical equivalence holds because incrementing n-1 elements is functionally identical to decrementing the single excluded element, allowing us to sum differences from the absolute minimum regardless of sign.
Extremely skewed distributions with a massive outlier
How to Handle:
The linear scan to find the minimum value and subsequent accumulation of differences execute efficiently in O(n) time without intermediate overflows.
Maximum-sized inputs up to array constraints
How to Handle:
An O(n) single-pass approach processing each element once ensures the solution scales efficiently and avoids timeout errors.
Integer overflow during the summation of moves
How to Handle:
Standard 32-bit integers can exceed capacity if the sum of differences is very large, so the handling uses 64-bit integer accumulators to prevent overflow.
0/257 completed