MediumNo. 0462

Minimum Moves to Equal Array Elements II — LeetCode 462 Python Solution

Pattern
Sorting
Topics
Array, Math, Sorting
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 or decrement an element of the array by 1.

Example

Input
nums = [1,2,3]
Output
2
Explanation
Only two moves are needed (remember each move increments or decrements one element):

Python solution

PythonSolution
class Solution:
    def minMoves2(self, nums: List[int]) -> int:
        nums.sort()
        k = nums[len(nums) >> 1]
        return sum(abs(v - k) for v in nums)

Complexity

Time
O(n log n)
Space · auxiliary
O(log n)

Pattern: Sorting

Spend O(n log n) once to buy an ordering that makes the rest of the problem trivial. LeetCode 462. Minimum Moves to Equal Array Elements II is filed here because LeetCode tags it Sorting, which is the vocabulary this hub collects.

The sorting guide has the Python template for the pattern and the 401 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 462. Minimum Moves to Equal Array Elements II?

LeetCode 462. Minimum Moves to Equal Array Elements II is rated Medium on LeetCode.

What is the time complexity of LeetCode 462. Minimum Moves to Equal Array Elements II?

The Python solution on this page runs in O(n log n).

What is the space complexity of LeetCode 462. Minimum Moves to Equal Array Elements II?

The Python solution on this page uses O(log n) auxiliary space.

What topics does LeetCode 462. Minimum Moves to Equal Array Elements II cover?

LeetCode 462. Minimum Moves to Equal Array Elements II is tagged Array, Math and Sorting 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.

Free to download. Check it runs on your machine, then pick a plan.