Problem 462

Abstract / Summary

Find the minimum moves to make all elements equal by moving values between elements, choosing the best target value.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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)
5 lines | 187 bytes | submitted January 6, 2024 | GitHub   20% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 62% (300k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Math
  • Sorting
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 8 | μ = 8.27 | σ = 1.16

Complexity Analysis

Time: loglinear
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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++
41 links | 26 authors | 10 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

7 similar problems

Solved On The Same Day

10 solutions   January 6, 2024

Extra

There are a few extra pages giving you some insights into my setup:
  • 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