#462
Minimum Moves to Equal Array Elements II
MediumArrayMathSortingSortingMedianArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n log n)Space O(1)
The optimal solution leverages the median of the array. By moving all elements to the median, we minimize the total distance moved. This is because the median minimizes the sum of absolute deviations.
⚙️
Algorithm
4 steps- 1Step 1: Sort the array.
- 2Step 2: Find the median of the array. If n is odd, it's the middle element; if even, either of the two middle elements will work.
- 3Step 3: Calculate the total moves required to make all elements equal to the median.
- 4Step 4: Return the total moves.
solution.py6 lines
1# Full working Python code
2
3def minMoves2(nums):
4 nums.sort()
5 median = nums[len(nums) // 2]
6 return sum(abs(num - median) for num in nums)ℹ
Complexity note: The time complexity is O(n log n) due to the sorting step. The space complexity is O(1) because we are using a constant amount of extra space.
- 1The median minimizes the total distance when moving numbers in a one-dimensional space.
- 2Sorting the array is crucial for efficiently finding the median.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.