Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Hash
  • Practice Hash
  • MCQs on Hash
  • Hashing Tutorial
  • Hash Function
  • Index Mapping
  • Collision Resolution
  • Open Addressing
  • Separate Chaining
  • Quadratic probing
  • Double Hashing
  • Load Factor and Rehashing
  • Advantage & Disadvantage
Open In App
Next Article:
Minimize count of divisions by D to obtain at least K equal array elements
Next article icon

Minimize count of divisions by 2 required to make all array elements equal

Last Updated : 15 Jun, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

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> 

Output: 
2

 

Time Complexity: O(N*log N)
Auxiliary Space: O(N)


Next Article
Minimize count of divisions by D to obtain at least K equal array elements

V

vandanakillari54935
Improve
Article Tags :
  • Hash
  • Technical Scripter
  • DSA
  • Arrays
  • Technical Scripter 2020
  • frequency-counting
Practice Tags :
  • Arrays
  • Hash

Similar Reads

  • Minimize cost of insertions and deletions required to make all array elements equal
    Given a sorted array arr[] of size N (1 ? N ? 105) and two integers A and B, the task is to calculate the minimum cost required to make all array elements equal by increments or decrements. The cost of each increment and decrement are A and B respectively. Examples: Input: arr[] = { 2, 5, 6, 9, 10,
    11 min read
  • Minimize count of divisions by D to obtain at least K equal array elements
    Given an array A[ ] of size N and two integers K and D, the task is to calculate the minimum possible number of operations required to obtain at least K equal array elements. Each operation involves replacing an element A[i] by A[i] / D. This operation can be performed any number of times. Examples:
    9 min read
  • Minimize increments required to make count of even and odd array elements equal
    Given an array arr[] of size N, the task is to find the minimum increments by 1 required to be performed on the array elements such that the count of even and odd integers in the given array becomes equal. If it is not possible, then print "-1". Examples: Input: arr[] = {1, 3, 4, 9}Output: 1Explanat
    6 min read
  • Minimum changes required to make all element in an array equal
    Given an array of length N, the task is to find minimum operation required to make all elements in the array equal. Operation is as follows: Replace the value of one element of the array by one of its adjacent elements. Examples: Input: N = 4, arr[] = {2, 3, 3, 4} Output: 2 Explanation: Replace 2 an
    5 min read
  • Minimize division by 2 to make Array of alternate odd and even elements
    Given an array arr[] of N positive integers. The task is to find the minimum number of operations required to make the array containing alternating odd and even numbers. In one operation, any array element can be replaced by its half (i.e arr[i]/2). Examples: Input: N=6, arr = [4, 10, 6, 6, 2, 7]Out
    15+ min read
  • Minimize cost required to make all array elements greater than or equal to zero
    Given an array arr[] consisting of N integers and an integer X, the task is to find the minimum cost required to make all array elements greater than or equal to 0 by performing the following operations any number of times: Increase any array element by 1. Cost = 1.Increase all array elements by 1.
    7 min read
  • Minimum cost to make all array elements equal
    Given an array arr[] consisting of N positive integers, the task is to make all values of this array equal to some integer value with minimum cost after performing below operations any number of times (possibly zero). Reduce the array element by 2 or increase it by 2 with zero cost.Reduce the array
    5 min read
  • Minimize moves required to make array elements equal by incrementing and decrementing pairs | Set 2
    Given an array arr[] of size N, the task is to print the minimum number of moves required to make all array elements equal by selecting any pair of distinct indices and then increment the element at the first index and decrement the element at the other index by 1 each time. If it is impossible to m
    7 min read
  • Minimum operations required to make all the array elements equal
    Given an array arr[] of n integer and an integer k. The task is to count the minimum number of times the given operation is required to make all the array elements equal. In a single operation, the kth element of the array is appended at the end of the array and the first element of the array gets d
    6 min read
  • Minimize increments required to make differences between all pairs of array elements even
    Given an array, arr[] consisting of N integers, the task is to minimize the number of increments of array elements required to make all differences pairs of array elements even. Examples: Input: arr[] = {4, 1, 2}Output: 1Explanation: Operation 1: Increment arr[1] by 1. The array arr[] modifies to {4
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences