Minimum Moves to Equal Array Elements - Problem

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.

Note: Incrementing n - 1 elements is equivalent to decrementing one element by 1.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,2,3]
Output: 3
💡 Note: Need 3 moves: increment [1,2] by 1 (→[2,3,3]), increment [2,3] by 1 (→[3,4,3]), increment [3,4] by 1 (→[4,4,4]). Total: 3 moves.
Example 2 — All Equal
$ Input: nums = [1,1,1]
Output: 0
💡 Note: All elements are already equal, so no moves needed.
Example 3 — Larger Differences
$ Input: nums = [1,2,9]
Output: 9
💡 Note: Minimum is 1. Moves needed: (2-1) + (9-1) = 1 + 8 = 9 moves to equalize all to 1.

Constraints

  • 2 ≤ nums.length ≤ 105
  • -109 ≤ nums[i] ≤ 109

Visualization

Tap to expand
Minimum Moves to Equal Array Elements INPUT nums array: 1 index 0 2 index 1 3 index 2 Input Values: nums = [1, 2, 3] n = 3 elements Value Distribution: 1 2 3 ALGORITHM STEPS 1 Find Minimum min(nums) = 1 2 Key Observation Inc n-1 = Dec 1 element 3 Calculate Differences Each elem - min value 4 Sum All Differences Total moves needed Calculation: (1 - 1) = 0 moves (2 - 1) = 1 move (3 - 1) = 2 moves Total = 0 + 1 + 2 = 3 FINAL RESULT After 3 moves, all elements equal: 1 1 1 Output: 3 OK - Verified! Move Breakdown: Dec 2 once: [1,1,3] Dec 3 twice: [1,1,1] Total: 3 decrements Key Insight: Incrementing (n-1) elements by 1 is mathematically equivalent to decrementing 1 element by 1. To equalize all elements to the minimum value, we need sum(nums) - n * min(nums) moves. Formula: (1+2+3) - 3*1 = 6 - 3 = 3 moves | Time: O(n) | Space: O(1) TutorialsPoint - Minimum Moves to Equal Array Elements | Optimal Solution
Asked in
Google 45 Amazon 35 Microsoft 25 Facebook 20
125.0K Views
Medium Frequency
~15 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen