Minimum Moves to Equal Array Elements II — LeetCode 462 Python Solution
MediumArrayMathSorting
- Problem
- #462
- Pattern
- Sorting
- Reading time
- 2 min
- Source
- leetcode.com
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
Python
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
| Measure | Complexity |
|---|---|
| Time | O(n \log n) |
| Space | O(\log n) auxiliary |
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.