You are given a list of whole numbers, nums. In one move you pick any single number and either add 1 to it or subtract 1 from it.
Return the fewest moves needed to make every number in the list the same. The answer always fits in a 32-bit integer.
Example 1
Input: nums = [3, 8, 1, 6, 4] Output: 10 Why: make all of them 4: 1 + 4 + 3 + 2 + 0 = 10
2 more examples and the constraints
Example 2
Input: nums = [2, 7, 7, 11] Output: 9 Why: make all of them 7: 5 + 0 + 0 + 4 = 9
Example 3
Input: nums = [-4, 0, 5] Output: 9 Why: make all of them 0: 4 + 0 + 5 = 9
Constraints
- 1 ≤ length of nums ≤ 100,000
- −1,000,000,000 ≤ nums[i] ≤ 1,000,000,000
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Try every value as the targetO(n²)
- Sort, then pair the endsO(n log n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 100,000 numbers | Verdict |
|---|---|---|---|
| Try every value as the target | O(n²) | Mention it, then move on | |
| Sort, then pair the ends | O(n log n) | Best; a sort and one pass |
n = how many numbers are in the list.
Edge cases to test
- One number. It is already equal to itself: 0 moves.
- Even length. Any target between the two middle values works; pairing the ends never has to pick one.
- Far-apart values. −1,000,000,000 and 1,000,000,000 differ by 2,000,000,000, which overflows a 32-bit sum in some steps: add in 64 bits.
- Duplicates. [1, 2, 2, 2, 100] still meets at 2, the median.
Common mistakes
- Moving everything to the average. [1, 2, 2, 2, 100] has average 21.4, far worse than the median 2.
- Adding differences in 32-bit integers, which overflows on values near the limits.
- Confusing this with the version where a move adds 1 to all numbers but one.
How to talk through it
- 1Clarify. Can a move go up and down? Can values be negative? Does the answer fit in 32 bits?
- 2Give the brute force. Try each number as the target and sum the distances; say it is O(n²).
- 3Argue for the median. The smallest and largest cost b − a for any target between them; the same holds for each pair inward, and the median is inside every pair.
- 4Code the pair walk. Sort, then add
nums[hi] − nums[lo]while the pointers move toward each other. - 5Test out loud. Run one number, an even length and values near the limits before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?