The Wayback Machine - https://web.archive.org/web/20240624071652/https://www.geeksforgeeks.org/minimum-operation-make-elements-equal-array/
Open In App

Minimum operation to make all elements equal in array

Last Updated : 17 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array with n positive integers. We need to find the minimum number of operations to make all elements equal. We can perform addition, multiplication, subtraction, or division with any part on an array element. 

Examples: 

Input : arr[] = {1, 2, 3, 4}
Output : 3
Since all elements are different, 
we need to perform at least three
operations to make them same. For
example, we can make them all 1
by doing three subtractions. Or make
them all 3 by doing three additions.

Input : arr[] = {1, 1, 1, 1}
Output : 0

To make all elements equal you can select a target value and then you can make all elements equal to that. Now, for converting a single element to target value you can perform a single operation only once. In this manner, you can achieve your task in a maximum of n operations but you have to minimize this number of operations and for this, your selection of target is very important because if you select a target whose frequency in array is x then you have to perform only n-x more operations as you have already x elements equal to your target value. So finally, our task is reduced to finding the element with maximum frequency. This can be achieved by different means such as the iterative method in O(n^2), sorting in O(nlogn), and hashing in O(n) time complexity. 

Step-by-step approach:

  • Create an empty hash table to store the frequency of each element in the array.
  • Traverse the array and insert each element into the hash table. If an element is already present in the hash table, increment its frequency.
  • Find the maximum frequency of any element in the hash table.
  • The minimum number of operations required to make all elements equal is equal to the difference between the total number of elements in the array and the maximum frequency of any element in the hash table

Pseudocode:

minOperations(arr, n)
    // Step 1
    hashTable = {}
    // Step 2
    for i = 0 to n-1 do
        if arr[i] is in hashTable then
            hashTable[arr[i]] = hashTable[arr[i]] + 1
        else
            hashTable[arr[i]] = 1
        end if
    end for
    // Step 3
    maxCount = 0
    for key in hashTable do
        if hashTable[key] > maxCount then
            maxCount = hashTable[key]
        end if
    end for
    // Step 4
    return n - maxCount
end function

Implementation:

C++




// CPP program to find the minimum number of
// operations required to make all elements
// of array equal
#include <iostream>
#include <unordered_map>
#include <algorithm>
 
using namespace std;
 
int minOperation(int arr[], int n) {
    // Insert all elements in hash.
    unordered_map<int, int> hash;
    for (int i=0; i<n; i++) {
        if (hash.find(arr[i]) != hash.end()) {
            hash[arr[i]]++;
        } else {
            hash[arr[i]] = 1;
        }
    }
     
    // find the max frequency
    int max_count = 0;
    for (auto it : hash) {
        max_count = max(max_count, it.second);
    }
      
    // return result
    return (n - max_count);
}
 
/* Driver program to test above function */
int main() {
    int arr[] = {1, 5, 2, 1, 3, 2, 1};
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << minOperation(arr, n) << endl;
    return 0;
}
//This code is contributed by NarasingaNikhil


Java




// JAVA Code For Minimum operation to make
// all elements equal in array
import java.util.*;
 
class GFG {
     
    // function for min operation
    public static int minOperation (int arr[], int n)
    {
        // Insert all elements in hash.
       HashMap<Integer, Integer> hash = new HashMap<Integer,
                                           Integer>();
         
        for (int i=0; i<n; i++)
            if(hash.containsKey(arr[i]))
                hash.put(arr[i], hash.get(arr[i])+1);
            else hash.put(arr[i], 1);
         
        // find the max frequency
        int max_count = 0;
        Set<Integer> s = hash.keySet();
         
        for (int i : s)
            if (max_count < hash.get(i))
                max_count = hash.get(i);
      
        // return result
        return (n - max_count);
    }
     
    /* Driver program to test above function */
    public static void main(String[] args)
    {
        int arr[] = {1, 5, 2, 1, 3, 2, 1};
        int n = arr.length;
        System.out.print(minOperation(arr, n));
             
    }
}
   
// This code is contributed by Arnav Kr. Mandal.


Python3




# Python3 program to find the minimum
# number of operations required to
# make all elements of array equal
#from collections import defaultdict
 
# Function for min operation
# using hashing
def minOperation(arr, n):
    mp = {}
    max_freq = 0
    #update the map
    for i in arr:
        mp[i] = mp.get(i,0) + 1
    #finding max freq
    for i in mp:
        if mp[i] > max_freq:
            max_freq = mp[i]
    # if all elements have same freq we have to change n-1 elements
    if max_freq == 1:
        return n-1
    # we need to change only remaining elements
    return (n-max_freq)
     
         
       
# Driver Code
if __name__ == "__main__":
 
    arr = [1, 5, 2, 1, 3, 2, 1]
    n = len(arr)
    print(minOperation(arr, n))
     
# This code is contributed
# by Aditya Bharat


C#




// C# Code For Minimum operation to make
// all elements equal in array
using System;
using System.Collections.Generic;
     
class GFG
{
     
    // function for min operation
    public static int minOperation (int []arr, int n)
    {
        // Insert all elements in hash.
        Dictionary<int,int> m = new Dictionary<int,int>();
        for (int i = 0 ; i < n; i++)
        {
            if(m.ContainsKey(arr[i]))
            {
                var val = m[arr[i]];
                m.Remove(arr[i]);
                m.Add(arr[i], val + 1);
            }
            else
            {
                m.Add(arr[i], 1);
            }
        }
         
        // find the max frequency
        int max_count = 0;
        HashSet<int> s = new HashSet<int>(m.Keys);
         
        foreach (int i in s)
            if (max_count < m[i])
                max_count = m[i];
     
        // return result
        return (n - max_count);
    }
     
    /* Driver code */
    public static void Main(String[] args)
    {
        int []arr = {1, 5, 2, 1, 3, 2, 1};
        int n = arr.Length;
        Console.Write(minOperation(arr, n));
             
    }
}
 
// This code is contributed by 29AjayKumar


Javascript




<script>
 
// JavaScript Code For Minimum operation to make
// all elements equal in array
 
// function for min operation
function minOperation(arr, n) {
    // Insert all elements in hash.
    let hash = new Map();
 
    for (let i = 0; i < n; i++)
        if (hash.has(arr[i]))
            hash.set(arr[i], hash.get(arr[i]) + 1);
        else hash.set(arr[i], 1);
 
    // find the max frequency
    let max_count = 0;
    let s = hash.keys();
 
    for (let i of s)
        if (max_count < hash.get(i))
            max_count = hash.get(i);
 
    // return result
    return (n - max_count);
}
 
/* Driver program to test above function */
 
let arr = [1, 5, 2, 1, 3, 2, 1];
let n = arr.length;
document.write(minOperation(arr, n));
 
 
// This code is contributed by _saurabh_jaiswal
 
</script>


Output

4

Time Complexity: O(n)
Auxiliary Space: O(n)

This article is contributed by Ritik Malarya  



Similar Reads

Make all array elements equal to 0 by replacing minimum subsequences consisting of equal elements
Given an array arr[] of size N, the task is to make all array elements equal to 0 by replacing all elements of a subsequences of equal elements by any integer, minimum number of times. Examples: Input: arr[] = {3, 7, 3}, N = 3Output: 2Explanation:Selecting a subsequence { 7 } and replacing all its elements by 0 modifies arr[] to { 3, 3, 3 }. Select
5 min read
Make all elements of an array equal with the given operation
Given an array arr[] of n integers and an integer k. The task is to make all the elements of arr[] equal with the given operation. In a single operation, any non-negative number x ? k (can be a floating point value) can be added to any element of the array and k will be updated as k = k - x. Print Yes is possible else print No. Examples: Input: k =
5 min read
Minimum cost to equal all elements of array using two operation
Given an array arr[] of n positive integers. There are two operations allowed: Operation 1 : Pick any two indexes, increase value at one index by 1 and decrease value at another index by 1. It will cost a. Operation 2 : Pick any index and increase its value by 1. It will cost b. The task is to find the minimum cost to make all the elements equal in
8 min read
Make all the elements of equal by using given operation
Given an array A[] of length N, the task is to return the minimum number of times the below-given operations are required to perform so that all elements become equal. If it is not possible then return -1. Choose two distinct indices i and j. Such that A[i] &gt; A[j]Let X = Ceil((A[i] - A[j])/2)Subtract X from A[i]Add X into A[j]Examples: Input: N
8 min read
Minimum sum of values subtracted from array elements to make all array elements equal
Given an array arr[] consisting of N positive integers, the task is to find the sum of all the array elements required to be subtracted from each array element such that remaining array elements are all equal. Examples: Input: arr[] = {1, 2}Output: 1Explanation: Subtracting 1 from arr[1] modifies arr[] to {1, 1}. Therefore, the required sum is 1. I
4 min read
Make all array elements equal by reducing array elements to half minimum number of times
Given an array arr[] consisting of N integers, the task is to minimize the number of operations required to make all array elements equal by converting Ai to Ai / 2. in each operation Examples: Input: arr[] = {3, 1, 1, 3}Output: 2Explanation: Reducing A0 to A0 / 2 modifies arr[] to {1, 1, 1, 3}. Reducing A3 to A3 / 2 modifies arr[] to {1, 1, 1, 1}.
6 min read
Minimum number of bits of array elements required to be flipped to make all array elements equal
Given an array arr[] consisting of N positive integers, the task is to find the minimum number of bits of array elements required to be flipped to make all array elements equal. Examples: Input: arr[] = {3, 5}Output: 2Explanation:Following are the flipping of bits of the array elements required: For element arr[0](= 3): Flipping the 3rd bit from th
7 min read
Minimum increment and decrement by K of each pair elements required to make all array elements equal
Given an array arr[], the task is to check if it is possible to make all array elements equal by repeatedly choosing a triplet (i, j, k), where i and j are different, and subtract k from arr[i] and add k to arr[j]. Examples: Input: arr[] = {1, 5, 6, 4}Output: YesExplanation:Operations performed: Choose i = 2, j = 0, k = 2 and perform the given oper
10 min read
Minimum steps to make X equal to Y by performing increment or bitwise OR operation
Given two integers X and Y, the task is to find the minimum number of operations required to make X equal to Y by performing the given operations such that: X = X + 1Y = Y + 1X = X | Y Examples: Input: X = 4, Y = 5Output: 1Explanation: Applying 1st operation one time X = X + 1 =&gt; 4 + 1 =&gt; 5 (Thus, both numbers become equal). Input: X = 2, Y =
10 min read
minimum operation to make every leaf node equal
Given a binary tree that contains multiple nodes, the task is to find a minimum number of operations required to make leaf nodes at the same level equal. By performing one operation you can either increase the node's value by one or decrease the node's value by one. Examples: Input: 6 / \ 4 2 / \ / \ 1 9 5 3 /10 Output: 6Explanation: There is no le
13 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg