Minimum operation to make all elements equal in array
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++ 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 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 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# 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 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));
Output
3
[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++ 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 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 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# 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 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));
Output
3
[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++ 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 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 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# 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 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));
Output
3