Minimum Moves to Equal Array Elements II — LeetCode #462 (Medium)
Tags: Array, Math, Sorting
Related patterns: Sorting, Median, Array
Brute Force approach
Time complexity: O(n²). Space complexity: O(1).
In the brute force approach, we calculate the cost to make all elements equal to each possible target value in the array. This means we check every number in the array as a potential target and sum the moves needed to reach that target from all other numbers.
The time complexity is O(n²) because for each of the n elements, we calculate the moves for all n elements, resulting in n * n operations. The space complexity is O(1) as we are using only a few extra variables.
- Step 1: Initialize a variable to store the minimum moves as infinity.
- Step 2: For each element in the array, consider it as a target value.
- Step 3: For each target, calculate the total moves required to make all elements equal to this target.
- Step 4: Update the minimum moves if the current target's moves are less than the previously recorded minimum.
- Step 5: Return the minimum moves found.
For nums = [1, 2, 3]:
1. Target = 1: Moves = |1-1| + |2-1| + |3-1| = 0 + 1 + 2 = 3
2. Target = 2: Moves = |1-2| + |2-2| + |3-2| = 1 + 0 + 1 = 2
3. Target = 3: Moves = |1-3| + |2-3| + |3-3| = 2 + 1 + 0 = 3
Final minimum moves = 2.
Optimal Solution approach
Time complexity: O(n log n). Space complexity: 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.
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.
- Step 1: Sort the array.
- Step 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.
- Step 3: Calculate the total moves required to make all elements equal to the median.
- Step 4: Return the total moves.
For nums = [1, 10, 2, 9]:
1. Sort: [1, 2, 9, 10]
2. Median = 9 (at index 2)
3. Moves = |1-9| + |2-9| + |9-9| + |10-9| = 8 + 7 + 0 + 1 = 16.
Key Insights
- The median minimizes the total distance when moving numbers in a one-dimensional space.
- Sorting the array is crucial for efficiently finding the median.
Common Mistakes
- Not considering the median and trying to move all numbers to the mean instead.
- Overlooking the need to sort the array before finding the median.
Interview Tips
- Always explain your thought process clearly, especially when transitioning from brute force to optimal solutions.
- Be prepared to discuss the implications of choosing the median over other potential targets.
- Practice explaining the time and space complexities of your solutions.