Last updated on January 21st, 2025 at 02:14 am
Here, we see a Minimum Moves to Equal Array Elements LeetCode Solution. This Leetcode problem is solved using different approaches in many programming languages, such as C++, Java, JavaScript, Python, etc.
List of all LeetCode Solution
Topics
Math
Companies
Level of Question
Medium

Minimum Moves to Equal Array Elements LeetCode Solution
Table of Contents
1. Problem Statement
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 n – 1 elements of the array by 1.
Example 1:
Input: nums = [1,2,3]
Output: 3
Explanation: Only three moves are needed (remember each move increments two elements): [1,2,3] => [2,3,3] => [3,4,3] => [4,4,4]
Example 2:
Input: nums = [1,1,1]
Output: 0
2. Coding Pattern Used in Solution
The coding pattern used here fall into “Mathematical Reduction” pattern. This pattern involves reducing a problem to a mathematical formula or observation to achieve an optimal solution.
3. Code Implementation in Different Languages
3.1 Minimum Moves to Equal Array Elements C++
class Solution { public: int minMoves(vector<int>& nums) { int m=INT_MAX; for(int n:nums) m = min(m,n); int ans=0; for(int n:nums) ans+=n-m; return ans; } };
3.2 Minimum Moves to Equal Array Elements Java
class Solution { public int minMoves(int[] nums) { if(nums==null||nums.length<=1) return 0; long min=(long)nums[0]; long sum=0; for(int i=0;i<nums.length;i++){ sum+=(long)nums[i]; min=Math.min(min,nums[i]); } return (int)(sum-min*nums.length); } }
3.3 Minimum Moves to Equal Array Elements JavaScript
var minMoves = function(nums) { if(nums == null || nums.length<=1) return 0; let min = nums[0] let sum = 0 for( i = 0;i< nums.length;i++){ sum += nums[i] min = Math.min(min,nums[i]) } return sum-min*nums.length };
3.4 Minimum Moves to Equal Array Elements Python
class Solution(object): def minMoves(self, nums): return sum(nums) - (len(nums) * min(nums))
4. Time and Space Complexity
Time Complexity | Space Complexity | |
C++ | O(n) | O(1) |
Java | O(n) | O(1) |
JavaScript | O(n) | O(1) |
Python | O(n) | O(1) |
- The time complexity is O(n) for all implementations because the algorithm iterates through the array once or twice.
- The space complexity is O(1) for all implementations because no additional data structures are used.