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. For example, if the input is nums = [1,2,3]
, the output should be 2
because [1,2,3] => [2,2,3] => [2,2,2]
. As another example, if the input is nums = [1,10,2,9]
, the output should be 16
. What approach would you take to solve this problem efficiently, and how would you handle potential edge cases such as an empty array or very large numbers?
# Minimum Moves to Equal Array Elements
## Problem Description
Given an integer array `nums` of size `n`, the task is to find 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.
For example:
- Input: `nums = [1, 2, 3]`
- Output: `2`
- Explanation: `[1, 2, 3] -> [2, 2, 3] -> [2, 2, 2]` (2 moves)
- Input: `nums = [1, 10, 2, 9]`
- Output: `16`
## Naive Approach
A naive approach would be to try every possible target value (i.e., every value between the min and max element of the array) and calculate the moves needed to convert all elements to that target value. Then, return the minimum of these moves.
```python
def min_moves_naive(nums):
min_val = min(nums)
max_val = max(nums)
min_moves = float('inf')
for target in range(min_val, max_val + 1):
moves = 0
for num in nums:
moves += abs(num - target)
min_moves = min(min_moves, moves)
return min_moves
This approach has a time complexity of O(n * (max - min)), where n is the length of the array and max and min are the maximum and minimum values in the array. This can be inefficient when the range (max - min) is large.
The optimal approach involves finding the median of the array. The minimum moves required will be achieved when all elements are made equal to the median. This is because the median minimizes the sum of absolute differences.
Here's the optimized solution:
def min_moves_optimal(nums):
nums.sort()
median = nums[len(nums) // 2]
moves = 0
for num in nums:
moves += abs(num - median)
return moves
nums.sort()
has a time complexity of O(n log n), where n is the number of elements in the array.Therefore, the overall time complexity is O(n log n), dominated by the sorting step.
Therefore, the overall space complexity is O(1) if the sorting is done in place and O(n) otherwise.
Here's how to handle the empty array edge case:
def min_moves_optimal(nums):
if not nums:
return 0 # Or raise an exception
nums.sort()
median = nums[len(nums) // 2]
moves = 0
for num in nums:
moves += abs(num - median)
return moves