Python 0462.py
class Solution:
def minMoves2(self, nums: List[int]) -> int:
nums.sort()
middle = nums[len(nums) // 2] # median
return sum(abs(n - middle) for n in nums)
Difficulty
and has an acceptance rate of about 62% (300k+ submissions).
Typical patterns to solve this problem:
- Array
- Math
- Sorting
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation solves the problem of finding the minimum number of moves required to make all elements of an integer array equal, where a single move consists of incrementing or decrementing an element by one. The algorithm leverages the statistical property that the sum of absolute deviations from a set of numbers is minimized at the median. By sorting the input and selecting the median element, the solution computes the total distance each element must travel to converge on that median, which directly yields the minimal move count.
Key Steps
Sorting the Input
The first operation arranges the numbers in non-decreasing order, which is essential for locating the median index reliably.
nums.sort()
Sorting transforms the unsorted collection into an ordered sequence, guaranteeing that the element at the middle index truly represents the median for both odd and even sized arrays.
Determining the Median
The median is obtained by indexing the sorted list at the integer division of its length by two. For an odd-length list, this picks the exact middle element; for an even-length list, it selects the upper middle element, which is a valid median choice because any value between the two central elements yields the same total absolute deviation.
middle = nums[len(nums) // 2] # median
Accumulating Absolute Differences
The final step iterates over the sorted array, computes the absolute difference between each element and the median, and aggregates these differences. The sum represents the total number of unit moves needed.
return sum(abs(n - middle) for n in nums)
Edge Cases Handled
When the input array contains a single element, the sorting step leaves the array unchanged, the median resolves to that sole element, and the generator expression yields zero for the absolute difference, resulting in a return value of zero moves.
If the array consists of duplicate values, the median will be one of those repeated numbers, and each absolute difference will be zero, again producing a zero move count.
For even-length arrays, the integer division used to compute the median index selects the higher of the two central elements. Because the sum of absolute deviations is flat between the two central values, this selection does not affect the correctness of the result.
The algorithm also gracefully handles negative numbers because the absolute difference calculation is sign-agnostic; the distance to the median is correctly measured regardless of sign.
Performance Optimizations
The solution’s primary optimization lies in reducing the problem to a single pass after sorting. By sorting once, the median can be accessed in constant time, and the subsequent generator expression computes the total deviation without auxiliary data structures.
The use of Python’s built-in sort method ensures an efficient in-place sort that benefits from highly tuned C-level implementations, providing fast execution for typical input sizes.
The generator expression inside sum avoids constructing an intermediate list of differences, thereby minimizing memory overhead and allowing the interpreter to process each element lazily. This design choice contributes to a lean runtime profile, especially for large arrays.
Overall, the combination of an optimal statistical insight (median minimization) with Python’s efficient built-ins yields a concise and performant solution.
ELI5 - Simplified Explanation
Imagine a long line of numbered toy blocks scattered on the floor. The goal is to make every single block have the exact same number on it. To do this using the fewest number of moves, the best secret trick is to find the happy middle number.
First, the code lines up all the blocks in order from the smallest number to the largest number. Because there is a clear order, the block sitting right in the middle is the most important one. This middle block acts like a anchor for all the others.
Once the middle anchor is found, the code looks at every individual block one by one. It sees how far each block is from the middle number. If a block is far away from the middle, it takes more steps to reach it, and if it is close, it takes fewer steps. By adding up all these little distances together, the code calculates the total amount of work needed to make all the blocks match the middle one.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||||
| www | AlgoMonster | C++ | Python | Java | TS | ||||||
| WalkCCC | C++ | Python | Java | ||||||||
| leetcode.ca | C++ | Python | Java | Rust | Go | TS | |||||
| LeetcodeHelp | C++ | Python | Java | ||||||||
| MemoryLimitExceeded | C++ | Python | |||||||||
| Progiez | C++ | Python | Java | ||||||||
| github | black-shadows | C++ | |||||||||
| charles-wangkai | Java | ||||||||||
| everthis | JS | ||||||||||
| fartem | Ruby | ||||||||||
| fpdjsns | C++ | ||||||||||
| fsq | C++ | ||||||||||
| halfrost | Go | ||||||||||
| JoshCrozier | JS | ||||||||||
| linouk23 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| MacJim | C++ | ||||||||||
| ruoru | Rust | ||||||||||
| suxrobGM | C# | ||||||||||
| trung-hn | Python | ||||||||||
| varunu28 | Java | ||||||||||
| vthwang | Java | ||||||||||
| wisdompeak | C++ | ||||||||||
| yuanliu666 | Kotlin | ||||||||||
| YuriSpiridonov | Python | ||||||||||
| zfang399 | C++ | ||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||
| WalkCCC | C++, Python, Java | ||||||||||
| leetcode.ca | C++, Go, Java, Python, Rust, TypeScript | ||||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||||
| MemoryLimitExceeded | Python, C++ | ||||||||||
| Progiez | C++, Java, Python | ||||||||||
| black-shadows | C++, C++ | ||||||||||
| charles-wangkai | Java | ||||||||||
| everthis | JavaScript | ||||||||||
| fartem | Ruby | ||||||||||
| fpdjsns | C++ | ||||||||||
| fsq | C++ | ||||||||||
| halfrost | Go | ||||||||||
| JoshCrozier | JavaScript | ||||||||||
| linouk23 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| MacJim | C++ | ||||||||||
| ruoru | Rust | ||||||||||
| suxrobGM | C# | ||||||||||
| trung-hn | Python | ||||||||||
| varunu28 | Java | ||||||||||
| vthwang | Java | ||||||||||
| wisdompeak | C++ | ||||||||||
| yuanliu666 | Kotlin | ||||||||||
| YuriSpiridonov | Python | ||||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 296: Best Meeting Point
- problem 453: Minimum Moves to Equal Array Elements
- problem 2033: Minimum Operations to Make a Uni-Value Grid
- problem 2171: Removing Minimum Number of Magic Beans
- problem 2448: Minimum Cost to Make Array Equal
- problem 2602: Minimum Operations to Make All Array Elements Equal
- problem 2967: Minimum Cost to Make Array Equalindromic
Solved On The Same Day
- problem 468: Validate IP Address
- problem 831: Masking Personal Information
- problem 874: Walking Robot Simulation
- problem 886: Possible Bipartition
- problem 1754: Largest Merge Of Two Strings
- problem 2055: Plates Between Candles
- problem 2086: Minimum Number of Food Buckets to Feed the Hamsters
- problem 2105: Watering Plants II
- problem 2816: Double a Number Represented as a Linked List
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality