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 Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Minimize divisions such that no Array element is divisible by K
Next article icon

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

Last Updated : 08 Jun, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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: 

Input: N = 5, A[ ] = {1, 2, 3, 4, 5}, K = 3, D = 2 
Output: 2 
Explanation: 
Step 1: Replace A[3] by A[3] / D, i.e. (4 / 2) = 2. Hence, the array modifies to {1, 2, 3, 2, 5} 
Step 2: Replace A[4] by A[4] / D, i.e. (5 / 2) = 2. Hence, the array modifies to {1, 2, 3, 2, 2} 
Hence, the modified array has K(= 3) equal elements. 
Hence, the minimum number of operations required is 2.

Input: N = 4, A[ ] = {1, 2, 3, 6}, K = 2, D = 3 
Output: 1 
Explanation:
Replacing A[3] by A[3] / D, i.e. (6 / 3) = 2. Hence, the array modifies to {1, 2, 3, 2}. 
Hence, the modified array has K(= 2) equal elements. 
Hence, the minimum number of operations required is 1. 

Naive Approach: 
The simplest approach to solve the problem is to generate every possible subset of the given array and perform the given operation on all elements of this subset. The number of operations required for each subset will be equal to the size of the subset. For each subset, count the number of equal elements and check if count is equal to K. If so, compare the then count with minimum moves obtained so far and update accordingly. Finally, print the minimum moves.

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

Efficient Approach: 
Follow the steps below to solve the problem: 

  • Initialize a 2D vector V, in which, size of a row V[i] denotes the number of array elements that have been reduced to A[i] and every element of the row denotes a count of divisions by D performed on an array element to obtain the number i.
  • Traverse the array. For each element A[i], keep dividing it by D until it reduces to 0.
  • For each intermediate value of A[i] obtained in the above step, insert the number of divisions required into V[A[i]].
  • Once, the above steps are completed for the entire array, iterate over the array V[ ].
  • For each V[i], check if the size of V[i] ? K (at most K).
  • If V[i] ? K, it denotes that at least K elements in the array have been reduced to i. Sort V[i] and add the first K values, i.e. the smallest K moves required to make K elements equal in the array.
  • Compare the sum of K moves with the minimum moves required and update accordingly.
  • Once the traversal of the array V[] is completed, print the minimum count of moves obtained finally.

Below is the implementation of the above approach:

C++




// C++ Program to implement
// the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to return minimum
// number of moves required
int getMinimumMoves(int n, int k, int d,
                    vector<int> a)
{
    int MAX = 100000;
 
    // Stores the number of moves
    // required to obtain respective
    // values from the given array
    vector<int> v[MAX];
 
    // Traverse the array
    for (int i = 0; i < n; i++) {
        int cnt = 0;
 
        // Insert 0 into V[a[i]] as
        // it is the initial state
        v[a[i]].push_back(0);
 
        while (a[i] > 0) {
            a[i] /= d;
            cnt++;
 
            // Insert the moves required
            // to obtain current a[i]
            v[a[i]].push_back(cnt);
        }
    }
 
    int ans = INT_MAX;
 
    // Traverse v[] to obtain
    // minimum count of moves
    for (int i = 0; i < MAX; i++) {
 
        // Check if there are at least
        // K equal elements for v[i]
        if (v[i].size() >= k) {
 
            int move = 0;
 
            sort(v[i].begin(), v[i].end());
 
            // Add the sum of minimum K moves
            for (int j = 0; j < k; j++) {
 
                move += v[i][j];
            }
 
            // Update answer
            ans = min(ans, move);
        }
    }
 
    // Return the final answer
    return ans;
}
 
// Driver Code
int main()
{
    int N = 5, K = 3, D = 2;
    vector<int> A = { 1, 2, 3, 4, 5 };
 
    cout << getMinimumMoves(N, K, D, A);
 
    return 0;
}
 
 

Java




// Java program to implement
// the above approach
import java.util.*;
 
class GFG{
 
// Function to return minimum
// number of moves required
@SuppressWarnings("unchecked")
static int getMinimumMoves(int n, int k,
                           int d, int[] a)
{
    int MAX = 100000;
 
    // Stores the number of moves
    // required to obtain respective
    // values from the given array
    Vector<Integer> []v = new Vector[MAX];
    for(int i = 0; i < v.length; i++)
        v[i] = new Vector<Integer>();
         
    // Traverse the array
    for(int i = 0; i < n; i++)
    {
        int cnt = 0;
 
        // Insert 0 into V[a[i]] as
        // it is the initial state
        v[a[i]].add(0);
 
        while (a[i] > 0)
        {
            a[i] /= d;
            cnt++;
 
            // Insert the moves required
            // to obtain current a[i]
            v[a[i]].add(cnt);
        }
    }
 
    int ans = Integer.MAX_VALUE;
 
    // Traverse v[] to obtain
    // minimum count of moves
    for(int i = 0; i < MAX; i++)
    {
         
        // Check if there are at least
        // K equal elements for v[i]
        if (v[i].size() >= k)
        {
            int move = 0;
 
            Collections.sort(v[i]);
 
            // Add the sum of minimum K moves
            for(int j = 0; j < k; j++)
            {
                move += v[i].get(j);
            }
 
            // Update answer
            ans = Math.min(ans, move);
        }
    }
 
    // Return the final answer
    return ans;
}
 
// Driver Code
public static void main(String[] args)
{
    int N = 5, K = 3, D = 2;
    int []A = { 1, 2, 3, 4, 5 };
 
    System.out.print(getMinimumMoves(N, K, D, A));
}
}
 
// This code is contributed by Amit Katiyar
 
 

Python3




# Python3 program to implement
# the above approach
 
# Function to return minimum
# number of moves required
def getMinimumMoves(n, k, d, a):
 
    MAX = 100000
 
    # Stores the number of moves
    # required to obtain respective
    # values from the given array
    v = []
    for i in range(MAX):
        v.append([])
 
    # Traverse the array
    for i in range(n):
        cnt = 0
 
        # Insert 0 into V[a[i]] as
        # it is the initial state
        v[a[i]] += [0]
 
        while(a[i] > 0):
            a[i] //= d
            cnt += 1
 
            # Insert the moves required
            # to obtain current a[i]
            v[a[i]] += [cnt]
 
    ans = float('inf')
 
    # Traverse v[] to obtain
    # minimum count of moves
    for i in range(MAX):
 
        # Check if there are at least
        # K equal elements for v[i]
        if(len(v[i]) >= k):
            move = 0
            v[i].sort()
 
            # Add the sum of minimum K moves
            for j in range(k):
                move += v[i][j]
 
            # Update answer
            ans = min(ans, move)
 
    # Return the final answer
    return ans
 
# Driver Code
if __name__ == '__main__':
 
    N = 5
    K = 3
    D = 2
    A = [ 1, 2, 3, 4, 5 ]
 
    # Function call
    print(getMinimumMoves(N, K, D, A))
 
# This code is contributed by Shivam Singh
 
 

C#




// C# program to implement
// the above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function to return minimum
// number of moves required
 
static int getMinimumMoves(int n, int k,
                           int d, int[] a)
{
    int MAX = 100000;
 
    // Stores the number of moves
    // required to obtain respective
    // values from the given array
    List<int> []v = new List<int>[MAX];
    for(int i = 0; i < v.Length; i++)
        v[i] = new List<int>();
         
    // Traverse the array
    for(int i = 0; i < n; i++)
    {
        int cnt = 0;
 
        // Insert 0 into V[a[i]] as
        // it is the initial state
        v[a[i]].Add(0);
 
        while (a[i] > 0)
        {
            a[i] /= d;
            cnt++;
 
            // Insert the moves required
            // to obtain current a[i]
            v[a[i]].Add(cnt);
        }
    }
 
    int ans = int.MaxValue;
 
    // Traverse v[] to obtain
    // minimum count of moves
    for(int i = 0; i < MAX; i++)
    {
         
        // Check if there are at least
        // K equal elements for v[i]
        if (v[i].Count >= k)
        {
            int move = 0;
 
            v[i].Sort();
 
            // Add the sum of minimum K moves
            for(int j = 0; j < k; j++)
            {
                move += v[i][j];
            }
 
            // Update answer
            ans = Math.Min(ans, move);
        }
    }
 
    // Return the final answer
    return ans;
}
 
// Driver Code
public static void Main(String[] args)
{
    int N = 5, K = 3, D = 2;
    int []A = { 1, 2, 3, 4, 5 };
 
    Console.Write(getMinimumMoves(N, K, D, A));
}
}
 
// This code is contributed by 29AjayKumar
 
 

Javascript




<script>
 
// JavaScript Program to implement
// the above approach
 
 
// Function to return minimum
// number of moves required
function getMinimumMoves(n, k, d,a)
{
    let MAX = 100000;
 
    // Stores the number of moves
    // required to obtain respective
    // values from the given array
    let v = new Array(MAX).fill(0).map(()=>new Array());
 
    // Traverse the array
    for (let i = 0; i < n; i++) {
        let cnt = 0;
 
        // Insert 0 into V[a[i]] as
        // it is the initial state
        v[a[i]].push(0);
 
        while (a[i] > 0) {
            a[i] = Math.floor(a[i] / d);
            cnt++;
 
            // Insert the moves required
            // to obtain current a[i]
            v[a[i]].push(cnt);
        }
    }
 
    let ans = Number.MAX_VALUE;
 
    // Traverse v[] to obtain
    // minimum count of moves
    for (let i = 0; i < MAX; i++) {
 
        // Check if there are at least
        // K equal elements for v[i]
        if (v[i].length >= k) {
 
            let move = 0;
 
            v[i].sort((a,b)=>a-b);
 
            // Add the sum of minimum K moves
            for (let j = 0; j < k; j++) {
 
                move += v[i][j];
            }
 
            // Update answer
            ans = Math.min(ans, move);
        }
    }
 
    // Return the final answer
    return ans;
}
 
// driver code
 
let N = 5, K = 3, D = 2;
let A = [ 1, 2, 3, 4, 5 ];
 
document.write(getMinimumMoves(N, K, D, A),"</br>");
 
// This code is contributed by shinjanpatra
 
</script>
 
 
Output
2

Time Complexity: O(MlogM), where M is the maximum number taken 
Auxiliary Space: O(M)
 



Next Article
Minimize divisions such that no Array element is divisible by K
author
tariq1510985
Improve
Article Tags :
  • Arrays
  • DSA
  • Mathematical
  • Matrix
  • Searching
  • Sorting
  • cpp-vector
  • frequency-counting
  • subset
Practice Tags :
  • Arrays
  • Mathematical
  • Matrix
  • Searching
  • Sorting
  • subset

Similar Reads

  • Minimize count of divisions by 2 required to make all array elements equal
    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: 2Explanation:Operation 1: Divide arr[0] ( = 3) by 2. The array arr[] m
    8 min read
  • Count of Array elements to be divided by 2 to make at least K elements equal
    Given an integer array arr[] of size N, the task is to find the minimum number of array elements required to be divided by 2, to make at least K elements in the array equal.Example : Input: arr[] = {1, 2, 2, 4, 5}, N = 5, K = 3 Output: 1 Explanation: Dividing 4 by 2 modifies the array to {1, 2, 2, 2
    9 min read
  • Minimize count of array elements to be removed such that at least K elements are equal to their index values
    Given an array arr[](1- based indexing) consisting of N integers and a positive integer K, the task is to find the minimum number of array elements that must be removed such that at least K array elements are equal to their index values. If it is not possible to do so, then print -1. Examples: Input
    13 min read
  • Minimize divisions such that no Array element is divisible by K
    Given an array arr[] of size N and an integer K, the task is to find the minimum operations such that no variable is divisible by K. In each operation: Select any integer X from the array.Divide all occurrences of X by K. Examples: Input: arr[] = [2, 3, 4, 5], K = 2Output: 2Explanation:In the first
    6 min read
  • Minimize the maximum element in constructed Array with sum divisible by K
    Given two integers N and K, the task is to find the smallest value for maximum element of an array of size N consisting of positive integers whose sum of elements is divisible by K. Examples: Input: N = 4, K = 3Output: 2Explanation: Let the array be [2, 2, 1, 1]. Here, sum of elements of this array
    4 min read
  • Maximize count of 1s in an array by repeated division of array elements by 2 at most K times
    Given an array arr[] of size N and an integer K, the task to find the maximum number of array elements that can be reduced to 1 by repeatedly dividing any element by 2 at most K times. Note: For odd array elements, take its ceil value of division. Examples: Input: arr[] = {5, 8, 4, 7}, K = 5Output:
    6 min read
  • Minimum Bitwise OR operations to make any two array elements equal
    Given an array arr[] of integers and an integer K, we can perform the Bitwise OR operation between any array element and K any number of times. The task is to print the minimum number of such operations required to make any two elements of the array equal. If it is not possible to make any two eleme
    9 min read
  • Count array elements having exactly K divisors
    Given an array arr[] consisting of N integers and an integer K, the task is to count the number of array elements having exactly K divisors. Examples: Input: N = 5, arr[] = { 3, 6, 2, 9, 4 }, K = 2Output: 2Explanation: arr[0] (= 3) and arr[2] (= 2) have exactly 2 divisors. Input: N = 5, arr[] = { 3,
    14 min read
  • Minimum elements to be added in a range so that count of elements is divisible by K
    Given three integer K, L and R (range [L, R]), the task is to find the minimum number of elements the range must be extended by so that the count of elements in the range is divisible by K. Examples: Input: K = 3, L = 10, R = 10 Output: 2 Count of elements in L to R is 1. So to make it divisible by
    4 min read
  • Construct an Array of length N containing exactly K elements divisible by their positions
    Given two integers N and K, the task is to construct an array of length N containing exactly K elements divisible by their positions. Examples: Input: N = 6, K = 2Output: {5, 1, 2, 3, 4, 6}Explanation: Considering the above array:At Position 1, element 5 is divisible by 1At Position 2, element 1 is
    10 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