Python 0453.py
class Solution:
def minMoves(self, nums: List[int]) -> int:
return sum(nums) - min(nums) * len(nums)
Difficulty
and has an acceptance rate of about 59% (300k+ submissions).
Typical patterns to solve this problem:
- Array
- Math
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 defines a class Solution with a single method minMoves. The method receives a list of integers nums and returns an integer representing the minimum number of moves required to make all array elements equal, where a move consists of incrementing n-1 elements by one. The solution leverages a mathematical insight that the total number of required increments equals the sum of the array minus the product of the smallest element and the array length.
Key Steps
The core logic is expressed in a one-line return statement:
return sum(nums) - min(nums) * len(nums)
The first part, sum(nums), computes the aggregate of all elements in the input list. The second part, min(nums) * len(nums), calculates the total value that would be present if every element were equal to the smallest element in the original list. Subtracting the latter from the former yields the exact count of unit increments needed to raise all other elements up to the level of the minimum.
Edge Cases Handled
When the input list contains a single element, sum(nums) and min(nums) * len(nums) evaluate to the same value, resulting in a return value of zero. This correctly reflects that no moves are necessary when only one element exists.
If all elements are already identical, the minimum equals each element, and the subtraction again yields zero, indicating that the array is already in the desired state.
The implementation also gracefully handles lists that include negative numbers. Since the mathematical relationship holds regardless of sign, the subtraction correctly computes the number of moves needed to align all values to the smallest (most negative) element.
Performance Optimizations
The solution performs only two linear scans over the input list: one to compute the sum and another to find the minimum value. Both operations are built-in Python functions that are highly optimized in C, minimizing interpreter overhead. By avoiding explicit loops or auxiliary data structures, the method reduces memory footprint and leverages the speed of native implementations.
The multiplication by len(nums) is a constant-time arithmetic operation, and the final subtraction is also constant time. Consequently, the overall execution path consists of a minimal number of high-performance primitive operations, making the method efficient for large input sizes.
ELI5 - Simplified Explanation
Imagine a group of friends sitting in a circle, each holding a different number of shiny trading cards. To make the game fair, everyone wants to have the exact same number of cards. The rules say that in one turn, almost everyone gets to pick up one new card at the same time, except for one person who has to sit out. To figure out how many turns it takes to make everyone equal, think about how many extra cards exist beyond what the person with the fewest cards has. First, count all the cards the group has altogether. Then, look at the person with the smallest pile and imagine giving everyone else enough cards so they match that smallest pile size. By subtracting the smallest number multiplied by the total amount of people from the big pile of all the cards combined, the answer shows how many turns are needed to get everyone to the same amount.
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++ | Java | Python | TS | |||||
| WalkCCC | C++ | Java | Python | |||||||
| leetcode.ca | C++ | Java | Python | Go | TS | |||||
| LeetcodeHelp | C++ | Java | Python | |||||||
| MemoryLimitExceeded | C++ | Python | ||||||||
| Progiez | C++ | Java | Python | |||||||
| github | BigEggStudy | C# | ||||||||
| black-shadows | C++ | |||||||||
| charles-wangkai | Java | |||||||||
| everthis | JS | |||||||||
| fartem | Ruby | |||||||||
| halfrost | Go | |||||||||
| JoshCrozier | JS | |||||||||
| keineahnung2345 | C++ | |||||||||
| linouk23 | C++ | |||||||||
| lkwq007 | Python | |||||||||
| lzl124631x | C++ | |||||||||
| qiyuangong | Java | |||||||||
| ruoru | Rust | |||||||||
| suxrobGM | C# | |||||||||
| varunu28 | Java | |||||||||
| wisdompeak | C++ | |||||||||
| zfang399 | C++ | |||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||
| WalkCCC | C++, Python, Java | |||||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | |||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||
| MemoryLimitExceeded | Python, C++ | |||||||||
| Progiez | C++, Java, Python | |||||||||
| BigEggStudy | C# | |||||||||
| black-shadows | C++, C++ | |||||||||
| charles-wangkai | Java | |||||||||
| everthis | JavaScript | |||||||||
| fartem | Ruby | |||||||||
| halfrost | Go | |||||||||
| JoshCrozier | JavaScript | |||||||||
| keineahnung2345 | C++ | |||||||||
| linouk23 | C++ | |||||||||
| lkwq007 | Python | |||||||||
| lzl124631x | C++ | |||||||||
| qiyuangong | Java | |||||||||
| ruoru | Rust | |||||||||
| suxrobGM | C# | |||||||||
| varunu28 | Java | |||||||||
| wisdompeak | C++ | |||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 462: Minimum Moves to Equal Array Elements II
- problem 3190: Find Minimum Operations to Make All Elements Divisible by Three
Solved On The Same Day
- problem 108: Convert Sorted Array to Binary Search Tree
- problem 482: License Key Formatting
- problem 72: Edit Distance
- problem 122: Best Time to Buy and Sell Stock II
- problem 167: Two Sum II - Input Array Is Sorted
- problem 515: Find Largest Value in Each Tree Row
- problem 535: Encode and Decode TinyURL
- problem 123: Best Time to Buy and Sell Stock III
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