Minimum Moves to Equal Array Elements II (LeetCode 462): Solution and Explanation
One move changes a single element of nums by 1, up or down. Find the fewest moves that make every element equal. The answer is the sum of distances to the median.
Intuition
If every element ends at a value t, the cost is the sum of |x - t|. The task is to choose t well.
Look at the smallest value a and the largest value b together. Any t between them costs exactly b - a for those two, and any t outside costs more.
Remove that pair and repeat with the next smallest and next largest. The intervals are nested, each one inside the previous.
The median lies inside every one of these intervals, so it pays the minimum for every pair at once. The answer is the sum of the pair spans.
Approach: Sort and pair from both ends
- Sort nums.
- Set i = 0 and j = n - 1.
- While i < j, add nums[j] - nums[i] to the total, then move i right and j left.
- Return the total. A middle element in an odd-length array is the median itself and adds 0.
Step-by-step example
nums = [1,10,2,9]
- Sorted: [1,2,9,10].
- Pair (1, 10) spans 9. moves = 9.
- Pair (2, 9) spans 7. moves = 16.
- The pointers cross. Any t from 2 to 9 is optimal; the answer is 16.
Code: Python, Java, C++
1class Solution:
2 def minMoves2(self, nums: List[int]) -> int:
3 nums.sort()
4 i, j = 0, len(nums) - 1
5 moves = 0
6 while i < j:
7 moves += nums[j] - nums[i]
8 i += 1
9 j -= 1
10 return moves1class Solution {
2 public int minMoves2(int[] nums) {
3 Arrays.sort(nums);
4 int i = 0, j = nums.length - 1;
5 long moves = 0;
6 while (i < j) {
7 moves += (long) nums[j] - nums[i];
8 i++;
9 j--;
10 }
11 return (int) moves;
12 }
13}1class Solution {
2public:
3 int minMoves2(vector<int>& nums) {
4 sort(nums.begin(), nums.end());
5 int i = 0, j = (int) nums.size() - 1;
6 long long moves = 0;
7 while (i < j) {
8 moves += (long long) nums[j] - nums[i];
9 i++;
10 j--;
11 }
12 return (int) moves;
13 }
14};Time and space complexity
O(n log n)
Sorting dominates; the two-pointer pass is linear.
O(1)
Sorting in place plus two pointers (ignoring the sort's own stack).
Other approaches
Quickselect the median (time O(n) expected, space O(1))
Find the median with quickselect in expected O(n), then add |x - median| over all elements.
Sort and sum distances to the median (time O(n log n), space O(1))
Sort, take nums[n / 2] and add |x - median|. The same answer as the two-pointer version, written differently.
Try every candidate target (time O(n^2), space O(1))
For each value as t, compute the total distance. Correct but quadratic.
Common mistakes
- Using the mean. The mean minimizes squared distance, not absolute distance, and can give a larger answer, for example [1, 0, 0, 8, 6].
- Overflow in the difference. nums[j] - nums[i] can reach 2 * 10^9, so compute it in 64 bits in Java, C++ and C#.
- Thinking even-length arrays need the average of the two middle values. Any t between them gives the same cost.
Frequently asked questions
Why the median and not the average?
Moving t one step toward the side with more elements lowers the cost, so the optimum has as many elements on each side as possible. That is the median. The average balances squared distances, which is a different problem.
What if n is even?
Every t between the two middle values is optimal and gives the same total. The two-pointer loop never needs to pick one.
How is this different from part I?
In part I a move raises n - 1 elements, which is the same as lowering one, so everything goes to the minimum. Here each element can move either way, so the median is best.