Problem 453

Abstract / Summary

Find the minimum steps needed to make all numbers in a list the same by adding or subtracting one from any element each move.

Note

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

Python 0453.py

class Solution:
    def minMoves(self, nums: List[int]) -> int:
        return sum(nums) - min(nums) * len(nums)
3 lines | 116 bytes | submitted August 21, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

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

Typical patterns to solve this problem:
  • Array
  • Math
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 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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 9 | μ = 8.33 | σ = 2.02

Complexity Analysis

Time: linear
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++ 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++
37 links | 23 authors | 9 languages

Videos

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

Similar Problems

2 similar problems

Solved On The Same Day

9 solutions   August 21, 2023

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