Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Minimum Moves to Equal Array Elements II in Python
Finding the minimum number of moves to make all array elements equal is a classic problem that can be solved efficiently using the median approach. A move consists of incrementing or decrementing any element by 1.
Algorithm Overview
The key insight is that the optimal target value is the median of the array. This minimizes the total distance (moves) needed to make all elements equal ?
Steps to Solve
- Sort the array to find the median easily
- Find the median element (middle element of sorted array)
- Calculate the sum of absolute differences between each element and the median
- Return the total moves required
Implementation
Here's the complete solution with detailed explanation ?
class Solution:
def minMoves2(self, nums):
# Sort the array to find median
nums.sort()
counter = 0
# Find median (middle element)
median = nums[len(nums) // 2]
# Calculate total moves needed
for num in nums:
counter += abs(num - median)
return counter
# Test with example
solution = Solution()
result = solution.minMoves2([2, 5, 3, 4])
print(f"Array: [2, 5, 3, 4]")
print(f"Minimum moves: {result}")
Array: [2, 5, 3, 4] Minimum moves: 4
Step-by-Step Execution
Let's trace through the example [2, 5, 3, 4] ?
nums = [2, 5, 3, 4]
print("Original array:", nums)
# Step 1: Sort the array
nums.sort()
print("Sorted array:", nums)
# Step 2: Find median
median = nums[len(nums) // 2]
print("Median:", median)
# Step 3: Calculate moves for each element
moves = []
for num in nums:
move = abs(num - median)
moves.append(move)
print(f"Element {num}: |{num} - {median}| = {move} moves")
total_moves = sum(moves)
print("Total moves:", total_moves)
Original array: [2, 5, 3, 4] Sorted array: [2, 3, 4, 5] Median: 4 Element 2: |2 - 4| = 2 moves Element 3: |3 - 4| = 1 moves Element 4: |4 - 4| = 0 moves Element 5: |5 - 4| = 1 moves Total moves: 4
Why Median Works
The median minimizes the sum of absolute deviations. For any other target value, the total moves would be greater than or equal to using the median ?
# Demonstrating why median is optimal
def calculate_moves(nums, target):
return sum(abs(num - target) for num in nums)
nums = [2, 3, 4, 5]
print("Comparing different targets:")
print(f"Target 2: {calculate_moves(nums, 2)} moves")
print(f"Target 3: {calculate_moves(nums, 3)} moves")
print(f"Target 4: {calculate_moves(nums, 4)} moves") # median
print(f"Target 5: {calculate_moves(nums, 5)} moves")
Comparing different targets: Target 2: 6 moves Target 3: 4 moves Target 4: 4 moves Target 5: 6 moves
Time and Space Complexity
| Aspect | Complexity | Reason |
|---|---|---|
| Time | O(n log n) | Sorting dominates |
| Space | O(1) | In-place sorting |
Conclusion
The minimum moves to equal array elements problem is solved optimally using the median as the target value. Sort the array, find the median, and sum the absolute differences from each element to the median.
