Minimum Moves to Equal Array Elements II - Problem

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

In one move, you can increment or decrement any element of the array by exactly 1. Your goal is to transform all elements to the same value using the fewest possible moves.

Example: If you have [1,2,3], you could make all elements equal to 2 by decrementing 3 to 2 (1 move) and incrementing 1 to 2 (1 move), for a total of 2 moves.

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

Input & Output

example_1.py โ€” Basic Case
$ Input: [1,2,3]
โ€บ Output: 2
๐Ÿ’ก Note: The median is 2. We need |1-2| + |2-2| + |3-2| = 1 + 0 + 1 = 2 moves to make all elements equal to 2.
example_2.py โ€” Even Length Array
$ Input: [1,10,2,9]
โ€บ Output: 16
๐Ÿ’ก Note: After sorting: [1,2,9,10]. The median can be either 2 or 9. Using 2 as target: |1-2| + |2-2| + |9-2| + |10-2| = 1 + 0 + 7 + 8 = 16 moves.
example_3.py โ€” Single Element
$ Input: [1]
โ€บ Output: 0
๐Ÿ’ก Note: Array with single element is already equal. No moves needed.

Constraints

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

Visualization

Tap to expand
Meeting Point Problem - Street ViewMain StreetHouse 1๐Ÿ‘คFriend AHouse 2๐Ÿ‘คFriend BMEETUP!House 3๐Ÿ‘คFriend C1 step1 stepWhy House 2 (Median) is Optimal:โ€ข Friend A walks 1 step (from house 1 to 2)โ€ข Friend B walks 0 steps (already at house 2)โ€ข Friend C walks 1 step (from house 3 to 2)
Understanding the Visualization
1
Identify Positions
Friends are at houses 1, 2, and 3 on the street
2
Find Optimal Meeting Point
The median house (house 2) minimizes total walking distance
3
Calculate Total Distance
Friend at house 1 walks 1 step, friend at house 2 walks 0 steps, friend at house 3 walks 1 step
Key Takeaway
๐ŸŽฏ Key Insight: The median minimizes the sum of absolute deviations because it balances the 'pull' from both sides equally, making it the optimal meeting point for minimizing total movement.
Asked in
Google 28 Amazon 22 Meta 18 Microsoft 15
38.4K Views
Medium Frequency
~12 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