Minimum Moves to Equal Array Elements II - 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 or decrement an element of the array by 1.

Test cases are designed so that the answer will fit in a 32-bit integer.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,2,3]
Output: 2
💡 Note: Only two moves are needed (remember that it is an array): [1,2,3] => [2,2,3] => [2,2,2]
Example 2 — Single Element
$ Input: nums = [1,10,2,9]
Output: 16
💡 Note: Sort to [1,2,9,10]. Median is 2 or 9, both give same result. Using median approach: target could be any value between 2 and 9, let's use 5.5 rounded to 6: |1-6| + |2-6| + |9-6| + |10-6| = 5+4+3+4 = 16. Actually optimal is median 2: |1-2| + |2-2| + |9-2| + |10-2| = 1+0+7+8 = 16
Example 3 — All Equal
$ Input: nums = [5,5,5]
Output: 0
💡 Note: All elements are already equal, so no moves needed

Constraints

  • n == nums.length
  • 1 ≤ n ≤ 105
  • -109 ≤ nums[i] ≤ 109

Visualization

Tap to expand
Minimum Moves to Equal Array Elements IIInput Array:123Target (Median = 2):2Moves needed:1 → 2: |1-2| = 1 move2 → 2: |2-2| = 0 moves3 → 2: |3-2| = 1 moveTotal Moves: 1 + 0 + 1 = 2
Understanding the Visualization
1
Input Array
Given array with different values
2
Find Target
Median minimizes total moves
3
Calculate Moves
Sum absolute differences to median
Key Takeaway
🎯 Key Insight: The median of a sorted array minimizes the sum of absolute deviations
Asked in
Google 15 Facebook 12 Microsoft 8 Amazon 6
125.0K Views
Medium Frequency
~15 min Avg. Time
1.9K 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