Minimum Moves to Equal Array Elements — LeetCode 453 Python Solution

MediumArrayMath
Problem
#453
Reading time
2 min

The problem

Given an integer array nums of size n, return the minimum number of moves required to make all array elements equal. In one move, you can increment n - 1 elements of the array by 1.

Example

Input
nums = [1,2,3]
Output
3
Explanation
Only three moves are needed (remember each move increments two elements):

Python solution

Python
class Solution:
    def minMoves(self, nums: List[int]) -> int:
        return sum(nums) - min(nums) * len(nums)

Complexity

MeasureComplexity
TimeO(n)
SpaceO(1) auxiliary

Pattern: Math and Number Theory

Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 453. Minimum Moves to Equal Array Elements is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Math.

The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 453. Minimum Moves to Equal Array Elements?
LeetCode 453. Minimum Moves to Equal Array Elements is rated Medium on LeetCode.
What is the time complexity of LeetCode 453. Minimum Moves to Equal Array Elements?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 453. Minimum Moves to Equal Array Elements?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 453. Minimum Moves to Equal Array Elements cover?
LeetCode 453. Minimum Moves to Equal Array Elements is tagged Array and Math on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview