Given an array arr[] consisting of N positive integers, the task is to find the minimum count of divisions(integer division) of array elements by 2 to make all array elements the same.
Examples:
Input: arr[] = {3, 1, 1, 3}
Output: 2
Explanation:
Operation 1: Divide arr[0] ( = 3) by 2. The array arr[] modifies to {1, 1, 1, 3}.
Operation 2: Divide arr[3] ( = 3) by 2. The array arr[] modifies to {1, 1, 1, 1}.
Therefore, the count of division operations required is 2.Input: arr[] = {2, 2, 2}
Output: 0
Approach: The idea to solve the given problem is to find the maximum number to which all the elements in the array can be reduced. Follow the steps below to solve the problem:
- Initialize a variable, say ans, to store the minimum count of division operations required.
- Initialize a HashMap, say M, to store the frequencies of array elements.
- Traverse the array arr[] until any array element arr[i] is found to be greater than 0. Keep dividing arr[i] by 2 and simultaneously update the frequency of the element obtained in the Map M.
- Traverse the HashMap and find the maximum element with frequency N. Store it in maxNumber.
- Again, traverse the array arr[] and find the number of operations required to reduce arr[i] to maxNumber by dividing arr[i] by 2 and add the count of operations to the variable ans.
- After completing the above steps, print the value of ans as the result.
Below is the implementation of the above approach:
C++
// C++ program for the above approach #include <bits/stdc++.h> using namespace std; Â
// Function to count minimum number of // division by 2 operations required to // make all array elements equal void makeArrayEqual( int A[], int n) {     // Stores the frequencies of elements     map< int , int > mp; Â
    // Stores the maximum number to     // which every array element     // can be reduced to     int max_number = 0; Â
    // Stores the minimum number     // of operations required     int ans = 0; Â
    // Traverse the array and store     // the frequencies in the map     for ( int i = 0; i < n; i++) { Â
        int b = A[i]; Â
        // Iterate while b > 0         while (b) {             mp[b]++; Â
            // Keep dividing b by 2             b /= 2;         }     } Â
    // Iterate over the map to find     // the required maximum number     for ( auto x : mp) { Â
        // Check if the frequency         // is equal to n         if (x.second == n) { Â
            // If true, store it in             // max_number             max_number = x.first;         }     } Â
    // Iterate over the array, A[]     for ( int i = 0; i < n; i++) {         int b = A[i]; Â
        // Find the number of operations         // required to reduce A[i] to         // max_number         while (b != max_number) { Â
            // Increment the number of             // operations by 1             ans++;             b /= 2;         }     } Â
    // Print the answer     cout << ans; } Â
// Driver Code int main() { Â Â Â Â int arr[] = { 3, 1, 1, 3 }; Â Â Â Â int N = sizeof (arr) / sizeof (arr[0]); Â Â Â Â makeArrayEqual(arr, N); Â
    return 0; } |
Java
/*package whatever //do not write package name here */ Â
import java.io.*; import java.util.Map; import java.util.HashMap; Â
class GFG {      // Function to count minimum number of   // division by 2 operations required to   // make all array elements equal   public static void makeArrayEqual( int A[], int n)   {          // Stores the frequencies of elements     HashMap<Integer, Integer> map = new HashMap<>(); Â
    // Stores the maximum number to     // which every array element     // can be reduced to     int max_number = 0 ; Â
    // Stores the minimum number     // of operations required     int ans = 0 ; Â
    // Traverse the array and store     // the frequencies in the map     for ( int i = 0 ; i < n; i++) { Â
      int b = A[i]; Â
      // Iterate while b > 0       while (b> 0 ) {         Integer k = map.get(b);         map.put(b, (k == null ) ? 1 : k + 1 ); Â
        // Keep dividing b by 2         b /= 2 ;       }     } Â
    // Iterate over the map to find     // the required maximum number     for (Map.Entry<Integer, Integer> e :          map.entrySet()) { Â
      // Check if the frequency       // is equal to n       if (e.getValue() == n) { Â
        // If true, store it in         // max_number         max_number = e.getKey();       }     } Â
    // Iterate over the array, A[]     for ( int i = 0 ; i < n; i++) {       int b = A[i]; Â
      // Find the number of operations       // required to reduce A[i] to       // max_number       while (b != max_number) { Â
        // Increment the number of         // operations by 1         ans++;         b /= 2 ;       }     } Â
    // Print the answer     System.out.println(ans + " " );   } Â
  // Driver Code   public static void main(String[] args)   {     int arr[] = { 3 , 1 , 1 , 3 };     int N = arr.length;     makeArrayEqual(arr, N);   } } Â
// This code is contributed by aditya7409. |
Python3
# Python 3 program for the above approach Â
# Function to count minimum number of # division by 2 operations required to # make all array elements equal def makeArrayEqual(A, n):      # Stores the frequencies of elements   mp = dict () Â
  # Stores the maximum number to   # which every array element   # can be reduced to   max_number = 0 Â
  # Stores the minimum number   # of operations required   ans = 0 Â
  # Traverse the array and store   # the frequencies in the map   for i in range (n):     b = A[i] Â
      # Iterate while b > 0     while (b> 0 ):       if (b in mp):         mp[b] + = 1       else :         mp[b] = mp.get(b, 0 ) + 1 Â
      # Keep dividing b by 2       b / / = 2 Â
  # Iterate over the map to find   # the required maximum number   for key,value in mp.items():          # Check if the frequency     # is equal to n     if (value = = n):              # If true, store it in       # max_number       max_number = key Â
  # Iterate over the array, A[]   for i in range (n):     b = A[i] Â
      # Find the number of operations       # required to reduce A[i] to       # max_number     while (b ! = max_number):              # Increment the number of       # operations by 1       ans + = 1       b / / = 2 Â
  # Print the answer   print (ans) Â
# Driver Code if __name__ = = '__main__' : Â Â arr = [ 3 , 1 , 1 , 3 ] Â Â N = len (arr) Â Â makeArrayEqual(arr, N) Â
  # This code is contributed by bgangwar59. |
C#
using System; using System.Collections.Generic; Â
class GFG {      // Function to count minimum number of   // division by 2 operations required to   // make all array elements equal   public static void makeArrayEqual( int [] A, int n)   {          // Stores the frequencies of elements     Dictionary< int , int > map = new Dictionary< int , int >(); Â
    // Stores the maximum number to     // which every array element     // can be reduced to     int max_number = 0; Â
    // Stores the minimum number     // of operations required     int ans = 0; Â
    // Traverse the array and store     // the frequencies in the map     for ( int i = 0; i < n; i++) { Â
      int b = A[i]; Â
      // Iterate while b > 0       while (b > 0)       {         if (map.ContainsKey(b))             map[b] ++;         else             map[b]= 1; Â
        // Keep dividing b by 2         b /= 2;       }     } Â
    // Iterate over the map to find     // the required maximum number     foreach (KeyValuePair< int , int > e in map)     { Â
      // Check if the frequency       // is equal to n       if (e.Value == n) { Â
        // If true, store it in         // max_number         max_number = e.Key;       }     } Â
    // Iterate over the array, A[]     for ( int i = 0; i < n; i++) {       int b = A[i]; Â
      // Find the number of operations       // required to reduce A[i] to       // max_number       while (b != max_number) { Â
        // Increment the number of         // operations by 1         ans++;         b /= 2;       }     } Â
    // Print the answer     Console.Write(ans + " " );   } Â
  // Driver Code   public static void Main(String[] args)   {     int [] arr = { 3, 1, 1, 3 };     int N = arr.Length;     makeArrayEqual(arr, N);   } } Â
// This code is contributed by shubhamsingh10. |
Javascript
<script> Â
// Javascript program for the above approach Â
// Function to count minimum number of // division by 2 operations required to // make all array elements equal function makeArrayEqual(A, n) {          // Stores the frequencies of elements     let mp = new Map(); Â
    // Stores the maximum number to     // which every array element     // can be reduced to     let max_number = 0; Â
    // Stores the minimum number     // of operations required     let ans = 0; Â
    // Traverse the array and store     // the frequencies in the map     for (let i = 0; i < n; i++)     {         let b = A[i]; Â
        // Iterate while b > 0         while (b)         {             if (mp.has(b))             {                 mp.set(b, mp.get(b) + 1)             }             else             {                 mp.set(b, 1)             } Â
            // Keep dividing b by 2             b = Math.floor(b / 2);         }     } Â
    // Iterate over the map to find     // the required maximum number     for (let x of mp)     {                  // Check if the frequency         // is equal to n         if (x[1] == n)         {                          // If true, store it in             // max_number             max_number = x[0];         }     } Â
    // Iterate over the array, A[]     for (let i = 0; i < n; i++)     {         let b = A[i]; Â
        // Find the number of operations         // required to reduce A[i] to         // max_number         while (b != max_number)         {                          // Increment the number of             // operations by 1             ans++;             b = Math.floor(b / 2);         }     }          // Print the answer     document.write(ans); } Â
// Driver Code let arr = [ 3, 1, 1, 3 ]; let N = arr.length Â
makeArrayEqual(arr, N); Â
// This code is contributed by gfgking Â
</script> |
2
Â
Time Complexity: O(N*log N)
Auxiliary Space: O(N)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!