> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Minimum Moves to Equal Array Elements II

> Tested Python solution for LeetCode 462 with 26 pytest cases. Generate a practice environment with lcpy.

LeetCode 462, [Medium](/catalog/medium). Topics: [Array](/catalog/topics/array), [Math](/catalog/topics/math), [Sorting](/catalog/topics/sorting). [View on LeetCode](https://leetcode.com/problems/minimum-moves-to-equal-array-elements-ii/description/).

Generate this problem as a practice environment: tested reference solution, 26 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 462   # by problem number
lcpy gen -s minimum_moves_to_equal_array_elements_ii   # by problem name
```

## 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`.

Test cases are designed so that the answer will fit in a **32-bit** integer.

### Examples

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

```
Input: nums = [1,10,2,9]
Output: 16
```

### Constraints

* n == nums.length
* 1 \<= nums.length \<= 10^5
* -10^9 \<= nums\[i] \<= 10^9
* The answer is guaranteed to fit in a 32-bit integer.

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/minimum_moves_to_equal_array_elements_ii/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/minimum_moves_to_equal_array_elements_ii/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
    # Time: O(n log n)
    # Space: O(n)
    def min_moves2(self, nums: list[int]) -> int:
        nums = sorted(nums)
        median = nums[len(nums) // 2]
        return sum(abs(num - median) for num in nums)
```

## Complexity

| Time | Space |
| - | - |
| O(n log n) | O(n) |

## Tags


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.