0462 - Minimum Moves to Equal Array Elements II (Medium)
Problem Link
https://leetcode.com/problems/minimum-moves-to-equal-array-elements-ii
Problem Statement
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 .
Test cases are designed so that the answer will fit in a 32-bit integer.
Example 1:
Input: nums = [1,2,3]
Output: 2
Explanation:
Only two moves are needed (remember each move increments or decrements one element):
[1,2,3] => [2,2,3] => [2,2,2]Example 2:
Input: nums = [1,10,2,9]
Output: 16Constraints:
n == nums.length1 <= nums.length <= 1e5-1e9 <= nums[i] <= 1e9
Approach 1: Sorting + Median
Since one move lets us increase or decrease exactly one number by , the total number of moves needed to make every value equal to some target is . So the problem becomes "which target minimizes the sum of absolute differences?"
The answer is the median of the array. Why?
- If we sort the array, numbers on the left of the target need to move right
- Numbers on the right of the target need to move left
- Choosing the median balances those two sides so that the total distance is as small as possible
Another way to see it is to pair the smallest and largest numbers after sorting. If we want both of them to become the same value , then the number of moves contributed by this pair is .
For any between and , this value is always , so it is already minimal. Applying this idea to all pairs shows that any median gives the minimum total moves.
That means the algorithm is straightforward:
- Sort
- Pick the middle element as the median
- Sum up for all elements
For example, if , after sorting we get .
- One valid median is (the code uses ).
- Total moves = .
The time complexity is and the space complexity is if we ignore the internal space used by the sorting implementation.
class Solution:
def minMoves2(self, nums: list[int]) -> int:
nums.sort()
m = nums[len(nums) // 2]
return sum(abs(x - m) for x in nums)