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
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read
Selection Sort Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted.First we find the smallest element an
8 min read