#453

Minimum Moves to Equal Array Elements

Medium
ArrayMathArrayMathematical Operations
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

Instead of incrementing elements, we can think of the problem as reducing all elements to the minimum element in the array. The number of moves required will be the difference between each element and the minimum element, summed up.

⚙️

Algorithm

3 steps
  1. 1Step 1: Find the minimum element in the array.
  2. 2Step 2: Calculate the total moves needed by summing the differences between each element and the minimum element.
  3. 3Step 3: Return the total moves.
solution.py5 lines
1# Full working Python code
2
3def minMoves(nums):
4    min_num = min(nums)
5    return sum(num - min_num for num in nums)

Complexity note: The time complexity is O(n) because we only need to traverse the array a couple of times: once to find the minimum and once to calculate the moves.

  • 1The problem can be viewed as reducing all elements to the minimum instead of incrementing others.
  • 2Understanding the operation's effect is crucial to finding the optimal solution.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.