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:
Smallest number to be added in first Array modulo M to make frequencies of both Arrays equal
Next article icon

Minimize increment/decrement of Array elements to make each modulo K equal

Last Updated : 15 Jan, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] of length N and an integer K. In each operation any element(say arr[i]) can be selected from the array and can be changed to arr[i] + 1 or arr[i] - 1. The task is to find the minimum number of operations required to perform on the array such that each value of the array modulo K remains the same.

Examples: 

Input: arr[] = {4, 5, 8, 3, 12},  k =5
Output: 4
Explanation:
Operation 1: { 3, 5, 8, 3, 12 }, decrease 4 at index 0 by 1.
Operation 2: { 3, 4, 8, 3, 12 }, decrease 5 at index 1 by 1.
Operation 3: { 3, 3, 8, 3, 12 }, decrease 4 at index 1 by 1.
Operation 4: { 3, 3, 8, 3, 13 }, increase 12 at index 4 by 1.
The modulo of each number is equal to 3 and minimum steps required were 4.

Input: arr[] = {2, 35, 48, 23, 52},  k =3
Output: 2
Explanation:
Minimum number of steps required to make modulo of each number equal is 2.

Approach: The idea is to use Hashing that keeps the count of each modulo that has been obtained.

  • Now iterate for each value of i, in range 0 <= i < k, and find the number of operation required to make the modulo of all numbers equal.
  • If it is less than the value obtained than the currently stored value then update it.

Below is the implementation of the above approach:

C++
// C++ program for the above approach #include <bits/stdc++.h> using namespace std;  // Function to find the minimum operations // required to make the modulo of each // element of the array equal to each other int Find_min(set<int>& diff_mod,              map<int, int> count_mod, int k) {     // Variable to store minimum     // operation required     int min_oprn = INT_MAX;      // To store operation required to     // make all modulo equal     int oprn = 0;      // Iterating through all     // possible modulo value     for (int x = 0; x < k; x++) {         oprn = 0;          // Iterating through all different         // modulo obtained so far         for (auto w : diff_mod) {              // Calculating oprn required             // to make all modulos equal             // to x             if (w != x) {                  if (w == 0) {                      // Checking the operations                     // that will cost less                     oprn += min(x, k - x)                             * count_mod[w];                 }                  else {                      // Check operation that                     // will cost less                     oprn += min(                                 abs(x - w),                                 k + x - w)                             * count_mod[w];                 }             }         }          // Update the minimum         // number of operations         if (oprn < min_oprn)             min_oprn = oprn;     }      // Returning the answer     return min_oprn; }  // Function to store different modulos int Cal_min(int arr[], int n, int k) {     // Set to store all     // different modulo     set<int> diff_mod;      // Map to store count     // of all different  modulo     // obtained     map<int, int> count_mod;      // Storing all different     // modulo count     for (int i = 0; i < n; i++) {          // Insert into the set         diff_mod.insert(arr[i] % k);          // Increment count         count_mod[arr[i] % k]++;     }      // Function call to return value of     // min oprn required     return Find_min(diff_mod, count_mod, k); }  // Driver Code int main() {     int arr[] = { 2, 35, 48, 23, 52 };     int n = sizeof(arr) / sizeof(arr[0]);     int k = 3;     cout << Cal_min(arr, n, k);     return 0; } 
Java
// Java program for the above approach import java.util.*;  class GFG{      // Function to find the minimum operations // required to make the modulo of each // element of the array equal to each other static int Find_min(HashSet<Integer> diff_mod,                     HashMap<Integer,                              Integer> count_mod,                     int k) {          // Variable to store minimum     // operation required     int min_oprn = Integer.MAX_VALUE;      // To store operation required to     // make all modulo equal     int oprn = 0;      // Iterating through all     // possible modulo value     for(int x = 0; x < k; x++)     {         oprn = 0;          // Iterating through all different         // modulo obtained so far         for(int w : diff_mod)          {              // Calculating oprn required             // to make all modulos equal             // to x             if (w != x)              {                 if (w == 0)                 {                                          // Checking the operations                     // that will cost less                     oprn += Math.min(x, k - x) *                             count_mod.get(w);                 }                 else                  {                                          // Check operation that                     // will cost less                     oprn += Math.min(Math.abs(x - w),                                       k + x - w) *                                       count_mod.get(w);                 }             }         }          // Update the minimum         // number of operations         if (oprn < min_oprn)             min_oprn = oprn;     }      // Returning the answer     return min_oprn; }  // Function to store different modulos static int Cal_min(int arr[], int n, int k) {          // Set to store all     // different modulo     HashSet<Integer> diff_mod = new HashSet<>();      // Map to store count     // of all different modulo     // obtained     HashMap<Integer,              Integer> count_mod = new HashMap<>();      // Storing all different     // modulo count     for(int i = 0; i < n; i++)      {                  // Insert into the set         diff_mod.add(arr[i] % k);          // Increment count         count_mod.put(arr[i] % k,          count_mod.getOrDefault(arr[i] % k, 0) + 1);     }      // Function call to return value of     // min oprn required     return Find_min(diff_mod, count_mod, k); }  // Driver Code public static void main(String[] args) {     int arr[] = { 2, 35, 48, 23, 52 };     int n = arr.length;     int k = 3;          System.out.print(Cal_min(arr, n, k)); } }  // This code is contributed by jrishabh99 
Python3
# Python3 program for  # the above approach import sys from collections import defaultdict  # Function to find the minimum operations # required to make the modulo of each # element of the array equal to each other def Find_min(diff_mod,              count_mod, k):      # Variable to store minimum     # operation required     min_oprn = sys.maxsize      # To store operation required to     # make all modulo equal     oprn = 0      # Iterating through all     # possible modulo value     for x in range (k):         oprn = 0          # Iterating through all different         # modulo obtained so far         for w in diff_mod:              # Calculating oprn required             # to make all modulos equal             # to x             if (w != x):                  if (w == 0):                      # Checking the operations                     # that will cost less                     oprn += (min(x, k - x) *                               count_mod[w])                                 else:                      # Check operation that                     # will cost less                     oprn += (min(abs(x - w),                                       k + x - w) *                                       count_mod[w])                    # Update the minimum         # number of operations         if (oprn < min_oprn):             min_oprn = oprn         # Returning the answer     return min_oprn  # Function to store different modulos def Cal_min(arr,  n, k):      # Set to store all     # different modulo     diff_mod = set([])      # Map to store count     # of all different  modulo     # obtained     count_mod = defaultdict (int)      # Storing all different     # modulo count     for i in range (n):          # Insert into the set         diff_mod.add(arr[i] % k)          # Increment count         count_mod[arr[i] % k] += 1         # Function call to return value of     # min oprn required     return Find_min(diff_mod, count_mod, k)  # Driver Code if __name__ == "__main__":       arr = [2, 35, 48, 23, 52]     n = len(arr)     k = 3     print( Cal_min(arr, n, k))      # This code is contributed by Chitranayal 
C#
// C# program for the above approach using System; using System.Collections.Generic;  class GFG{      // Function to find the minimum operations // required to make the modulo of each // element of the array equal to each other static int Find_min(HashSet<int> diff_mod,                     Dictionary<int,                                 int> count_mod,                     int k) {          // Variable to store minimum     // operation required     int min_oprn = int.MaxValue;      // To store operation required to     // make all modulo equal     int oprn = 0;      // Iterating through all     // possible modulo value     for(int x = 0; x < k; x++)     {         oprn = 0;          // Iterating through all different         // modulo obtained so far         foreach(int w in diff_mod)          {              // Calculating oprn required             // to make all modulos equal             // to x             if (w != x)              {                 if (w == 0)                 {                                          // Checking the operations                     // that will cost less                     oprn += Math.Min(x, k - x) *                             count_mod[w];                 }                 else                 {                                          // Check operation that                     // will cost less                     oprn += Math.Min(Math.Abs(x - w),                                       k + x - w) *                                       count_mod[w];                 }             }         }          // Update the minimum         // number of operations         if (oprn < min_oprn)             min_oprn = oprn;     }      // Returning the answer     return min_oprn; }  // Function to store different modulos static int Cal_min(int []arr, int n, int k) {          // Set to store all     // different modulo     HashSet<int> diff_mod = new HashSet<int>();      // Map to store count     // of all different modulo     // obtained     Dictionary<int,                 int> count_mod = new Dictionary<int,                                                int>();      // Storing all different     // modulo count     for(int i = 0; i < n; i++)      {                  // Insert into the set         diff_mod.Add(arr[i] % k);          // Increment count         if(count_mod.ContainsKey((arr[i] % k)))             count_mod[arr[i] % k] = count_mod[(arr[i] % k)]+1;         else             count_mod.Add(arr[i] % k, 1);     }      // Function call to return value of     // min oprn required     return Find_min(diff_mod, count_mod, k); }  // Driver Code public static void Main(String[] args) {     int []arr = { 2, 35, 48, 23, 52 };     int n = arr.Length;     int k = 3;          Console.Write(Cal_min(arr, n, k)); } }  // This code is contributed by Amit Katiyar  
JavaScript
<script>  // Javascript program for the above approach  // Function to find the minimum operations // required to make the modulo of each // element of the array equal to each other function Find_min(diff_mod, count_mod, k) {          // Variable to store minimum     // operation required     let min_oprn = Number.MAX_VALUE;       // To store operation required to     // make all modulo equal     let oprn = 0;       // Iterating through all     // possible modulo value     for(let x = 0; x < k; x++)     {         oprn = 0;                  // Iterating through all different         // modulo obtained so far         for(let w of diff_mod.values())         {                          // Calculating oprn required             // to make all modulos equal             // to x             if (w != x)             {                 if (w == 0)                 {                                          // Checking the operations                     // that will cost less                     oprn += Math.min(x, k - x) *                             count_mod.get(w);                 }                 else                 {                                          // Check operation that                     // will cost less                     oprn += Math.min(Math.abs(x - w),                                           k + x - w) *                                     count_mod.get(w);                 }             }         }                  // Update the minimum         // number of operations         if (oprn < min_oprn)             min_oprn = oprn;     }       // Returning the answer     return min_oprn; }  // Function to store different modulos function Cal_min(arr, n, k) {          // Set to store all     // different modulo     let diff_mod = new Set();       // Map to store count     // of all different modulo     // obtained     let count_mod = new Map();       // Storing all different     // modulo count     for(let i = 0; i < n; i++)     {                   // Insert into the set         diff_mod.add(arr[i] % k);           // Increment count         // Increment count         if(count_mod.has((arr[i] % k)))             count_mod.set(arr[i] % k,             count_mod.get(arr[i] % k) + 1);         else             count_mod.set(arr[i] % k, 1);      }       // Function call to return value of     // min oprn required     return Find_min(diff_mod, count_mod, k); }  // Driver Code let arr = [ 2, 35, 48, 23, 52 ]; let n = arr.length; let k = 3;  document.write(Cal_min(arr, n, k));  // This code is contributed by avanitrachhadiya2155  </script>   

Output: 
2

 

Time Complexity: O(N*K), where N is the length of the given array and K is the given value.
Auxiliary Space: O(N+K), where N is the length of the given array and K is the given value.


Next Article
Smallest number to be added in first Array modulo M to make frequencies of both Arrays equal
author
chsadik99
Improve
Article Tags :
  • Mathematical
  • Hash
  • Competitive Programming
  • C++ Programs
  • DSA
  • Arrays
  • Modular Arithmetic
Practice Tags :
  • Arrays
  • Hash
  • Mathematical
  • Modular Arithmetic

Similar Reads

  • Minimum operations of given type to make all elements of a matrix equal
    Given an integer K and a matrix of N rows and M columns, the task is to find the minimum number of operations required to make all the elements of the matrix equal. In a single operation, K can be added to or subtracted from any element of the matrix. Print -1 if it is impossible to do so. Examples:
    15+ min read
  • Minimum replacements required to have at most K distinct elements in the array
    Given an array arr[] consisting of N positive integers and an integer K, the task is to find the minimum number of array elements required to be replaced by the other array elements such that the array contains at most K distinct elements. Input: arr[] = { 1, 1, 2, 2, 5 }, K = 2 Output: 1 Explanatio
    13 min read
  • Smallest number to be added in first Array modulo M to make frequencies of both Arrays equal
    Given two arrays A[] and B[] consisting of N positive integers and an integer M, the task is to find the minimum value of X such that operation (A[i] + X) % M performed on every element of array A[] results in the formation of an array with frequency of elements same as that in another given array B
    8 min read
  • Maximum value of X such that difference between any array element and X does not exceed K
    Given an array arr[] consisting of N positive integers and a positive integer K, the task is to find the maximum possible integer X, such that the absolute difference between any array element and X is at most K. If no such value of X exists, then print "-1". Examples: Input: arr[] = {6, 4, 8, 5}, K
    11 min read
  • Minimum possible sum of array elements after performing the given operation
    Given an array arr[] of positive integers and an integer x, the task is to minimize the sum of elements of the array after performing the given operation at most once. In a single operation, any element from the array can be divided by x (if it is divisible by x) and at the same time, any other elem
    8 min read
  • Minimize array sum by replacing greater and smaller elements of pairs by half and double of their values respectively atmost K times
    Given an array arr[] consisting of N positive integers and an integer K, the task is to find the minimum possible array sum that can be obtained by repeatedly selecting a pair from the given array and divide one of the elements by 2 and multiply the other element by 2, at most K times. Examples: Inp
    15+ min read
  • Count minimum moves required to convert A to B
    Given two integers A and B, convert A to B by performing one of the following operations any number of times: A = A + KA = A - K, where K belongs to [1, 10] The task is to find the minimum number of operations required to convert A to B using the above operations. Examples: Input: A = 13, B = 42Outp
    4 min read
  • Minimum MEX from all subarrays of length K
    Given an array arr[] consisting of N distinct positive integers and an integer K, the task is to find the minimum MEX from all subarrays of length K. The MEX is the smallest positive integer that is not present in the array. Examples: Input: arr[] = {1, 2, 3}, K = 2Output: 1Explanation:All subarrays
    7 min read
  • Reduce given array by replacing subarrays with values less than K with their sum
    Given an array arr[] consisting of N positive integers and a positive integer K, the task is to update the given array by replacing the subarrays that are less than K with the sum of the elements in that subarray. Examples: Input: arr[] = {200, 6, 36, 612, 121, 66, 63, 39, 668, 108}, K = 100Output:
    6 min read
  • Length of longest subarray whose sum is not divisible by integer K
    Given an array arr[] of size N and an integer k, our task is to find the length of longest subarray whose sum of elements is not divisible by k. If no such subarray exists then return -1.Examples: Input: arr[] = {8, 4, 3, 1, 5, 9, 2}, k = 2 Output: 5 Explanation: The subarray is {8, 4, 3, 1, 5} with
    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