Minimum operation to make all elements equal in array
Last Updated :
22 Apr, 2025
Given an array consisting of n positive integers, the task is to find the minimum number of operations to make all elements equal. In each operation, we can perform addition, multiplication, subtraction, or division with any number and an array element.
Examples:
Input : arr[] = [1, 2, 3, 4]
Output : 3
Explanation: All element are different. Select any one element and make the other elements equal to selected element. For example, we can make them all 1 by doing three subtractions. Or make them all 3 by doing three additions.
Input: arr[] = [1, 2, 2, 3]
Output: 2
Explanation: Perform operation on 1 and 3 to make them equal to 2.
Input : arr[] = [1, 1, 1, 1]
Output : 0
Explanation: All elements are equal.
[Naive Approach] Using 2 Nested Loops – O(n^2) time and O(1) space
The idea is to try each element as a potential target value and count how many operations would be needed to transform all other elements into that target. The minimum number of operations will be the smallest count found among all possible target values.
C++
// C++ program to find Minimum operation
// to make all elements equal in array
#include <bits/stdc++.h>
using namespace std;
// Function to find the minimum number of operations
int minOperations(vector<int> &arr) {
int n = arr.size();
// Maximum possible operations would be n
int minOps = n;
// Try each element as the potential final value
for (int i = 0; i < n; i++) {
int currOps = 0;
// Count how many elements are different from arr[i]
for (int j = 0; j < n; j++) {
if (arr[i] != arr[j]) {
currOps++;
}
}
// Update minimum operations
minOps = min(minOps, currOps);
}
return minOps;
}
int main() {
vector<int> arr = {1, 2, 3, 4};
cout << minOperations(arr);
return 0;
}
Java
// Java program to find Minimum operation
// to make all elements equal in array
class GfG {
// Function to find the minimum number of operations
static int minOperations(int[] arr) {
int n = arr.length;
// Maximum possible operations would be n
int minOps = n;
// Try each element as the potential final value
for (int i = 0; i < n; i++) {
int currOps = 0;
// Count how many elements are different from
// arr[i]
for (int j = 0; j < n; j++) {
if (arr[i] != arr[j]) {
currOps++;
}
}
// Update minimum operations
minOps = Math.min(minOps, currOps);
}
return minOps;
}
public static void main(String[] args) {
int[] arr = { 1, 2, 3, 4 };
System.out.println(minOperations(arr));
}
}
Python
# Python program to find Minimum operation
# to make all elements equal in array
# Function to find the minimum number of operations
def minOperations(arr):
n = len(arr)
# Maximum possible operations would be n
minOps = n
# Try each element as the potential final value
for i in range(n):
currOps = 0
# Count how many elements are different from arr[i]
for j in range(n):
if arr[i] != arr[j]:
currOps += 1
# Update minimum operations
minOps = min(minOps, currOps)
return minOps
if __name__ == "__main__":
arr = [1, 2, 3, 4]
print(minOperations(arr))
C#
// C# program to find Minimum operation
// to make all elements equal in array
using System;
class GfG {
// Function to find the minimum number of operations
static int minOperations(int[] arr) {
int n = arr.Length;
// Maximum possible operations would be n
int minOps = n;
// Try each element as the potential final value
for (int i = 0; i < n; i++) {
int currOps = 0;
// Count how many elements are different from
// arr[i]
for (int j = 0; j < n; j++) {
if (arr[i] != arr[j]) {
currOps++;
}
}
// Update minimum operations
minOps = Math.Min(minOps, currOps);
}
return minOps;
}
static void Main(string[] args) {
int[] arr = { 1, 2, 3, 4 };
Console.WriteLine(minOperations(arr));
}
}
JavaScript
// JavaScript program to find Minimum operation
// to make all elements equal in array
// Function to find the minimum number of operations
function minOperations(arr) {
let n = arr.length;
// Maximum possible operations would be n
let minOps = n;
// Try each element as the potential final value
for (let i = 0; i < n; i++) {
let currOps = 0;
// Count how many elements are different from arr[i]
for (let j = 0; j < n; j++) {
if (arr[i] !== arr[j]) {
currOps++;
}
}
// Update minimum operations
minOps = Math.min(minOps, currOps);
}
return minOps;
}
let arr = [1, 2, 3, 4];
console.log(minOperations(arr));
[Better Approach] Using Sorting – O(n Log n) time and O(1) space
The idea is to sort the array to group identical elements together, then find the element with maximum frequency. Since each operation can change an element to any value, the optimal strategy is to change all other elements to match the most frequent element.
Step by step approach:
- Sort the array to group identical elements together.
- Scan through the sorted array and count frequencies of consecutive identical elements.
- Track the maximum frequency encountered.
- Calculate operations needed as (total elements – maximum frequency).
C++
// C++ program to find Minimum operation
// to make all elements equal in array
#include <bits/stdc++.h>
using namespace std;
// Function to find the minimum number of operations
int minOperations(vector<int> &arr) {
int n = arr.size();
// Sort the array
sort(arr.begin(), arr.end());
int maxFreq = 1;
int currFreq = 1;
// Count frequencies
for (int i = 1; i < n; i++) {
if (arr[i] == arr[i-1]) {
currFreq++;
} else {
maxFreq = max(maxFreq, currFreq);
currFreq = 1;
}
}
// Check final frequency
maxFreq = max(maxFreq, currFreq);
// Operations needed = total elements - maximum frequency
return n - maxFreq;
}
int main() {
vector<int> arr = {1, 2, 3, 4};
cout << minOperations(arr);
return 0;
}
Java
// Java program to find Minimum operation
// to make all elements equal in array
import java.util.*;
class GfG {
// Function to find the minimum number of operations
static int minOperations(int[] arr) {
int n = arr.length;
// Sort the array
Arrays.sort(arr);
int maxFreq = 1;
int currFreq = 1;
// Count frequencies
for (int i = 1; i < n; i++) {
if (arr[i] == arr[i - 1]) {
currFreq++;
} else {
maxFreq = Math.max(maxFreq, currFreq);
currFreq = 1;
}
}
// Check final frequency
maxFreq = Math.max(maxFreq, currFreq);
// Operations needed = total elements - maximum frequency
return n - maxFreq;
}
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4};
System.out.println(minOperations(arr));
}
}
Python
# Python program to find Minimum operation
# to make all elements equal in array
# Function to find the minimum number of operations
def minOperations(arr):
n = len(arr)
# Sort the array
arr.sort()
maxFreq = 1
currFreq = 1
# Count frequencies
for i in range(1, n):
if arr[i] == arr[i - 1]:
currFreq += 1
else:
maxFreq = max(maxFreq, currFreq)
currFreq = 1
# Check final frequency
maxFreq = max(maxFreq, currFreq)
# Operations needed = total elements - maximum frequency
return n - maxFreq
if __name__ == "__main__":
arr = [1, 2, 3, 4]
print(minOperations(arr))
C#
// C# program to find Minimum operation
// to make all elements equal in array
using System;
class GfG {
// Function to find the minimum number of operations
static int minOperations(int[] arr) {
int n = arr.Length;
// Sort the array
Array.Sort(arr);
int maxFreq = 1;
int currFreq = 1;
// Count frequencies
for (int i = 1; i < n; i++) {
if (arr[i] == arr[i - 1]) {
currFreq++;
} else {
maxFreq = Math.Max(maxFreq, currFreq);
currFreq = 1;
}
}
// Check final frequency
maxFreq = Math.Max(maxFreq, currFreq);
// Operations needed = total elements - maximum frequency
return n - maxFreq;
}
static void Main() {
int[] arr = {1, 2, 3, 4};
Console.WriteLine(minOperations(arr));
}
}
JavaScript
// JavaScript program to find Minimum operation
// to make all elements equal in array
// Function to find the minimum number of operations
function minOperations(arr) {
let n = arr.length;
// Sort the array
arr.sort((a, b) => a - b);
let maxFreq = 1;
let currFreq = 1;
// Count frequencies
for (let i = 1; i < n; i++) {
if (arr[i] === arr[i - 1]) {
currFreq++;
} else {
maxFreq = Math.max(maxFreq, currFreq);
currFreq = 1;
}
}
// Check final frequency
maxFreq = Math.max(maxFreq, currFreq);
// Operations needed = total elements - maximum frequency
return n - maxFreq;
}
let arr = [1, 2, 3, 4];
console.log(minOperations(arr));
[Expected Approach] Using Hash Map – O(n) time and O(n) space
The idea is to use a hash map to count the frequency of each unique element in a single pass, then find the element that appears most frequently. The minimum operations needed equals the number of elements that need to be changed to match the most frequent element.
Step by step approach:
- Create a hash map to store frequency counts for each unique value.
- Populate the map by counting occurrences of each element in the array.
- Find the maximum frequency among all elements in the map.
- Calculate operations needed as (total elements – maximum frequency).
C++
// C++ program to find Minimum operation
// to make all elements equal in array
#include <bits/stdc++.h>
using namespace std;
// Function to find the minimum number of operations
int minOperations(vector<int> &arr) {
int n = arr.size();
// Store frequency of each element
unordered_map<int, int> freqMap;
for (int i = 0; i < n; i++) {
freqMap[arr[i]]++;
}
// Find maximum frequency
int maxFreq = 0;
for (auto it : freqMap) {
maxFreq = max(maxFreq, it.second);
}
// Operations needed = total elements - maximum frequency
return n - maxFreq;
}
int main() {
vector<int> arr = {1, 2, 3, 4};
cout << minOperations(arr);
return 0;
}
Java
// Java program to find Minimum operation
// to make all elements equal in array
import java.util.*;
class GfG {
// Function to find the minimum number of operations
static int minOperations(int[] arr) {
int n = arr.length;
// Store frequency of each element
HashMap<Integer, Integer> freqMap = new HashMap<>();
for (int i = 0; i < n; i++) {
freqMap.put(arr[i], freqMap.getOrDefault(arr[i], 0) + 1);
}
// Find maximum frequency
int maxFreq = 0;
for (int val : freqMap.values()) {
maxFreq = Math.max(maxFreq, val);
}
// Operations needed = total elements - maximum frequency
return n - maxFreq;
}
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4};
System.out.println(minOperations(arr));
}
}
Python
# Python program to find Minimum operation
# to make all elements equal in array
# Function to find the minimum number of operations
def minOperations(arr):
n = len(arr)
# Store frequency of each element
freqMap = {}
for i in range(n):
freqMap[arr[i]] = freqMap.get(arr[i], 0) + 1
# Find maximum frequency
maxFreq = max(freqMap.values())
# Operations needed = total elements - maximum frequency
return n - maxFreq
if __name__ == "__main__":
arr = [1, 2, 3, 4]
print(minOperations(arr))
C#
// C# program to find Minimum operation
// to make all elements equal in array
using System;
using System.Collections.Generic;
class GfG {
// Function to find the minimum number of operations
static int minOperations(int[] arr) {
int n = arr.Length;
// Store frequency of each element
Dictionary<int, int> freqMap = new Dictionary<int, int>();
for (int i = 0; i < n; i++) {
if (!freqMap.ContainsKey(arr[i])) {
freqMap[arr[i]] = 0;
}
freqMap[arr[i]]++;
}
// Find maximum frequency
int maxFreq = 0;
foreach (var val in freqMap.Values) {
maxFreq = Math.Max(maxFreq, val);
}
// Operations needed = total elements - maximum frequency
return n - maxFreq;
}
static void Main() {
int[] arr = {1, 2, 3, 4};
Console.WriteLine(minOperations(arr));
}
}
JavaScript
// JavaScript program to find Minimum operation
// to make all elements equal in array
// Function to find the minimum number of operations
function minOperations(arr) {
let n = arr.length;
// Store frequency of each element
let freqMap = new Map();
for (let i = 0; i < n; i++) {
freqMap.set(arr[i], (freqMap.get(arr[i]) || 0) + 1);
}
// Find maximum frequency
let maxFreq = 0;
for (let val of freqMap.values()) {
maxFreq = Math.max(maxFreq, val);
}
// Operations needed = total elements - maximum frequency
return n - maxFreq;
}
let arr = [1, 2, 3, 4];
console.log(minOperations(arr));
Similar Reads
Minimum Cost to make all array elements equal using given operations
Given an array arr[] of positive integers and three integers A, R, M, where The cost of adding 1 to an element of the array is A,the cost of subtracting 1 from an element of the array is R andthe cost of adding 1 to an element and subtracting 1 from another element simultaneously is M. The task is t
12 min read
Minimum increment by k operations to make all elements equal
You are given an array of n-elements, you have to find the number of operations needed to make all elements of array equal. Where a single operation can increment an element by k. If it is not possible to make all elements equal print -1. Example : Input : arr[] = {4, 7, 19, 16}, k = 3Output : 10Inp
6 min read
Minimum operations required to make all the array elements equal
Given an array arr[] of n integer and an integer k. The task is to count the minimum number of times the given operation is required to make all the array elements equal. In a single operation, the kth element of the array is appended at the end of the array and the first element of the array gets d
6 min read
Minimum operations required to make two elements equal in Array
Given array A[] of size N and integer X, the task is to find the minimum number of operations to make any two elements equal in the array. In one operation choose any element A[i] and replace it with A[i] & X. where & is bitwise AND. If such operations do not exist print -1. Examples: Input:
9 min read
Minimum operations to make all elements equal using the second array
Given two arrays A[] and B[] both having N elements. Find the minimum number of operations to make all elements of A equal to the second array B. An operation comprises of: A[i] = A[i] - B[i], 0 <= i <= n-1 Note: If it's not possible to make array elements equal print -1.Examples: Input: A[] =
7 min read
Minimum number of increment-other operations to make all array elements equal.
We are given an array consisting of n elements. At each operation we can select any one element and increase rest of n-1 elements by 1. We have to make all elements equal performing such operation as many times you wish. Find the minimum number of operations needed for this. Examples: Input: arr[] =
5 min read
Minimum cost to make all array elements equal
Given an array arr[] consisting of N positive integers, the task is to make all values of this array equal to some integer value with minimum cost after performing below operations any number of times (possibly zero). Reduce the array element by 2 or increase it by 2 with zero cost.Reduce the array
5 min read
Minimum increment operations to make K elements equal
Given an array arr[] of N elements and an integer K, the task is to make any K elements of the array equal by performing only increment operations i.e. in one operation, any element can be incremented by 1. Find the minimum number of operations required to make any K elements equal.Examples: Input:
11 min read
Minimum Bitwise OR operations to make any two array elements equal
Given an array arr[] of integers and an integer K, we can perform the Bitwise OR operation between any array element and K any number of times. The task is to print the minimum number of such operations required to make any two elements of the array equal. If it is not possible to make any two eleme
9 min read
Make all array elements equal with minimum cost
Given an array of size n, the task is to make the value of all elements equal with minimum cost. The cost of changing a value from x to y is abs(x - y). Examples : Input: arr[] = [1, 100, 101]Output: 100Explanation: We can change all its values to 100 with minimum cost,|1 - 100| + |100 - 100| + |101
15 min read