Leetcode 462. Minimum Moves to Equal Array Elements II

Problem Explanation

We are given a non-empty array of integers, with a maximum length of 10,000. The task is to make all elements in the array equal with the fewest possible moves. A move consists of either incrementing or decrementing an element by 1.

For example, consider the array [1,2,3]. In one move, we can increment the first element to get the array [2,2,3]. In another move, we can decrement the last element to get the array [2,2,2]. Thus, it takes 2 moves to make all elements equal in this array.

Approach

The solution involves finding the median of the elements in the array. By making all elements equal to the median, we can use the fewest number of moves.

The median is the middle value in an ordered list of numbers. If the list contains an even number of values, the median is the average of the two middle numbers. We can find the median efficiently using the ```

nth_element```

function, which partially sorts the array such that the nth element is in the position it would be in a fully sorted array.

After finding the median, we then accumulate (sum) the absolute differences between each element and the median. This sum represents the minimal number of moves required to make all elements equal.

Python Solution

1
2python
3from typing import List
4import statistics
5
6class Solution:
7  def minMoves2(self, nums: List[int]) -> int:
8    median = statistics.median(nums)
9    return sum(abs(num - median) for num in nums)

Java Solution

1
2java
3import java.util.*;
4
5class Solution {
6  public int minMoves2(int[] nums) {
7    Arrays.sort(nums);
8    int median = nums[nums.length / 2];
9    int moves = 0;
10    for (int num : nums) {
11      moves += Math.abs(num - median);
12    }
13    return moves;
14  }
15}

JavaScript Solution

1
2javascript
3class Solution {
4  minMoves2(nums) {
5    nums.sort((a, b) => a - b);
6    let median = nums[Math.floor(nums.length / 2)];
7    let moves = 0;
8    for (let num of nums) {
9      moves += Math.abs(num - median);
10    }
11    return moves;
12  }
13}

C++ Solution

1
2cpp
3#include <algorithm>
4#include <vector>
5using namespace std;
6
7class Solution {
8 public:
9  int minMoves2(vector<int>& nums) {
10    nth_element(nums.begin(), nums.begin() + nums.size() / 2, nums.end());
11    int median = nums[nums.size() / 2];
12    int moves = 0;
13    for(int num : nums) {
14      moves += abs(num - median);
15    }
16    return moves;
17  }
18};

C# Solution

1
2csharp
3using System;
4
5public class Solution {
6    public int MinMoves2(int[] nums) {
7        Array.Sort(nums);
8        int median = nums[nums.Length / 2];
9        int moves = 0;
10        foreach(int num in nums) {
11            moves += Math.Abs(num - median);
12        }
13        return moves;
14    }
15}

In all of the solutions, we first locate the median of the array. After that, we loop through the array and accumulate the absolute differences between each element and the median to find the minimum number of moves.## Complexity Analysis

In terms of time complexity, the Python solution has a complexity of O(n log n) due to the sort operation. Similarly, in the Java, JavaScript and C# solutions, the time complexity is O(n log n) due to the Arrays.sort function call.

In the C++ solution, the use of the nth_element function means that the median can be found in linear time, giving a time complexity of O(n). The resulting time complexity is dominated by the use of the function nth_element.

In terms of space complexity, all the solutions have a space complexity of O(1) because no extra space is required aside from the given input.

It's worth noting that if we don't have the inbuilt sorting function, we can also use the QuickSelect algorithm to find the median, which has an average time complexity of O(n) and worst-case time complexity of O(n^2). However, in practice, QuickSelect tends to be efficient due to its probabilistic nature.

In conclusion, while the python, Java, JavaScript and C# solutions are easier to write and understand, the C++ solution provides a more efficient approach to the problem. Depending on the requirements and constraints of your task, you may choose to use a different approach.


Got a question? Ask the Teaching Assistant anything you don't understand.

Still not clear? Ask in the Forum,  Discord or Submit the part you don't understand to our editors.


TA 👨‍🏫