Minimum operation to make all elements equal in array - GeeksforGeeks

08 Mar, 2022
Given an array with n positive integers. We need to find the minimum number of operation to make all elements equal. We can perform addition, multiplication, subtraction or division with any element 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
 
For making 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 maximum of n operations but you have to minimize this number of operation 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 iterative method in O(n^2), sorting in O(nlogn) and hashing in O(n) time complexity.  
C++
Java
Python3
C#
Javascript
// CPP program to find the minimum number of// operations required to make all elements// of array equal#include <bits/stdc++.h>using namespace std; // function for min operationint minOperation (int arr[], int n){    // Insert all elements in hash.    unordered_map<int, int> hash;    for (int i=0; i<n; i++)        hash[arr[i]]++;     // find the max frequency    int max_count = 0;    for (auto i : hash)        if (max_count < i.second)            max_count = i.second;     // return result    return (n - max_count);} // driver programint main(){    int arr[] = {1, 5, 2, 1, 3, 2, 1};    int n = sizeof(arr) / sizeof(arr[0]);    cout << minOperation(arr, n);    return 0;}
// JAVA Code For Minimum operation to make// all elements equal in arrayimport 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 program to find the minimum# number of operations required to# make all elements of array equalfrom collections import defaultdict # Function for min operationdef minOperation(arr, n):     # Insert all elements in hash.    Hash = defaultdict(lambda:0)    for i in range(0, n):        Hash[arr[i]] += 1     # find the max frequency    max_count = 0    for i in Hash:        if max_count < Hash[i]:            max_count = Hash[i]     # return result    return n - max_count # Driver Codeif __name__ == "__main__":     arr = [1, 5, 2, 1, 3, 2, 1]    n = len(arr)    print(minOperation(arr, n))     # This code is contributed# by Rituraj Jain
// C# Code For Minimum operation to make// all elements equal in arrayusing 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
<script> // JavaScript Code For Minimum operation to make// all elements equal in array // function for min operationfunction 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 Shivam Pradhan (anuj_charm). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
rituraj_jain
29AjayKumar
_saurabh_jaiswal
singhh3010
cpp-unordered_map
Arrays
Hash
Arrays
Hash
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Stack Data Structure (Introduction and Program)
Introduction to Arrays
Multidimensional Arrays in Java
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Internal Working of HashMap in Java
Count pairs with given sum
Hashing | Set 1 (Introduction)
Hashing | Set 3 (Open Addressing)