Magicsheet logo

Minimum Moves to Equal Array Elements

Medium
97.8%
Updated 6/1/2025

Minimum Moves to Equal Array Elements

1. What is this problem about?

In "Minimum Moves to Equal Array Elements," you are given an array of n integers. In one move, you can increment n - 1 elements by 1. The goal is to find the minimum number of moves to make all elements in the array equal.

This sounds like a complicated balancing act, but it has a very clever mathematical shortcut that transforms it from a simulation problem into a simple arithmetic one.

2. Why is this asked in interviews?

Companies like Microsoft and Amazon ask this to see if a candidate can think outside the box. Key challenges:

  • Mathematical Equivalence: Realizing that incrementing n1n-1 elements is mathematically equivalent to decrementing one element in terms of relative differences.
  • Efficiency: Solving the problem in O(n)O(n) time rather than trying to simulate the increments.
  • Optimization: Finding the "target" value without complex calculations.

3. Algorithmic pattern used

The pattern is Mathematical Reduction. If our goal is to make all elements equal, and we can increment n1n-1 elements at a time, we are essentially reducing the gap between the largest element and the rest. Equivalently, you can think of it as: "How many times do I need to decrement elements until they all reach the value of the minimum element in the array?" The formula is: Sum(array) - (min_element * n).

4. Example explanation

Array: [1, 2, 3]

  1. Min element = 1.
  2. Total sum = 1+2+3=61 + 2 + 3 = 6.
  3. Result = 6(1×3)=36 - (1 \times 3) = 3.

Let's verify by incrementing n1n-1 (which is 2) elements:

  • [1, 2, 3] \rightarrow Increment 1 and 2: [2, 3, 3] (1 move)
  • [2, 3, 3] \rightarrow Increment 2 and 3: [3, 4, 3] (No, that's not right). Wait, let's increment the two smallest:
  • [1, 2, 3] \rightarrow [2, 3, 3] (1 move)
  • [2, 3, 3] \rightarrow [3, 4, 3] (No, increment 2 and 3) \rightarrow [3, 3, 4] (2 moves)
  • [3, 3, 4] \rightarrow [4, 4, 4] (3 moves) It works! And the formula 63=36 - 3 = 3 gave us the answer immediately.

5. Common mistakes candidates make

  • Brute Force Simulation: Actually trying to increment n1n-1 elements in a loop. This is O(moves×n)O(moves \times n), which is extremely slow if the numbers are large.
  • Misunderstanding the Move: Thinking they can choose any number of elements to increment.
  • Incorrect Target: Trying to reach the maximum element. Since you can only increment n1n-1 elements, the "relative" maximum keeps moving up.

6. Interview preparation tip

When an operation affects "all but one" element, always try to rephrase the problem in terms of that "one" element. It often simplifies the logic significantly. This is a common pattern in "Equalizing" problems.

Similar Questions