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 II Two Pointers from Ends Approach INPUT Original Array: nums 1 idx 0 2 idx 1 3 idx 2 After Sorting: 1 2 median 3 Two Pointers: left=0 right=2 n = 3 elements ALGORITHM STEPS 1 Sort Array [1,2,3] already sorted 2 Initialize Pointers left=0, right=n-1, moves=0 3 Calculate Difference moves += nums[r] - nums[l] 4 Move Pointers left++, right-- until cross Iteration: l=0, r=2: nums[2]-nums[0] = 3 - 1 = 2 moves = 0 + 2 = 2 l=1, r=1: pointers crossed STOP - return moves FINAL RESULT All elements become median (2): Before: 1 2 3 After: 2 2 2 +1 move 0 moves -1 move Output: 2 OK - Minimum moves! Key Insight: The optimal target is the MEDIAN of the sorted array. The two-pointer approach calculates total moves by summing (nums[right] - nums[left]) as pointers move inward. This works because each pair contributes exactly their difference to total moves, regardless of the actual median value. TutorialsPoint - Minimum Moves to Equal Array Elements II | Two Pointers from Ends
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