Minimum operations required to make all Array elements divisible by K

Given an array a[], integer K and an integer X (which is initially initialized to 0). Our task is to find the minimum number of moves required to update the array such that each of its element is divisible by K by performing the following operations:

  • Choose one index i from 1 to N and increase ai by X and then increase X by 1. This operation cannot be applied more than once to each element of the array
  • Only increase the value of X by 1.

Examples:

Input: K = 3, a = [1, 2, 2, 18] 
Output:
Explanation: 
Initially X = 0 hence update X to 1. 
For X = 1 add X to the second element of array to make the array [1, 3, 2, 18] and increase X by 1. 
For X = 2 add X to the first element of array [3, 3, 2, 18] and increase X by 1. 
For X = 3 just increase X by 1. 
For X = 4 add X to the third element of array to make the array [3, 3, 6, 18] and increase X by 1. 
At last, the array becomes [3, 3, 6, 18] where all the elements are divisible by K = 3.

Input: K = 5, a[] = [15, 25, 5, 10, 20, 1005, 70, 80, 90, 100] 
Output:
Explanation: 
Here all elements are already divisible by 5.

Approach: The main idea is to find the maximum value of X that is needed to update the elements of the array to make it divisible by K.



  • To do this we need to find the maximum value of (K – (ai mod K)) to add to the array elements to make it divisible by K.
  • However, there can be equal elements so keep track of the number of such elements, using map data structures.
  • When found another such element in the array then update the answer with (K – (ai mod K)) + (K * number of Equal Elements) because with every move we increase X by 1.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation to find the 
// Minimum number of moves required to 
// update the array such that each of 
// its element is divisible by K 
  
#include <bits/stdc++.h> 
using namespace std; 
  
// Function to find the 
// Minimum number of moves required to 
// update the array such that each of 
// its element is divisible by K 
void compute(int a[], int N, int K) 
    // Initialize Map data structure 
    map<long, long> eqVal; 
  
    long maxX = 0; 
  
    // Iterate for all the elements 
    // of the array 
    for (int i = 0; i < N; i++) { 
  
        // Calculate the 
        // value to be added 
        long val = a[i] % K; 
  
        val = (val == 0 ? 0 : K - val); 
  
        // Check if the value equals 
        // to 0 then simply continue 
        if (val == 0) 
            continue
  
        // Check if the value to be 
        // added is present in the map 
        if (eqVal.find(val) != eqVal.end()) { 
  
            long numVal = eqVal[val]; 
            // Update the answer 
            maxX = max(maxX, 
                    val + (K * numVal)); 
  
            eqVal[val]++; 
        
  
        else
            eqVal[val]++; 
            maxX = max(maxX, val); 
        
    
  
    // Print the required result 
    // We need to add 1 to maxX 
    // because we cant ignore the 
    // first move where initially X=0 
    // and we need to increase it by 1 
    // to make some changes in array 
    cout << (maxX == 0 ? 0 : maxX + 1) 
        << endl; 
  
// Driver code 
int main() 
    int K = 3; 
    int a[] = { 1, 2, 2, 18 }; 
    int N = sizeof(a) / sizeof(a[0]); 
    compute(a, N, K); 
    return 0; 

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java implementation to find the 
// minimum number of moves required to 
// update the array such that each of 
// its element is divisible by K 
import java.util.*; 
  
class GFG{ 
      
// Function to find the minimum 
// number of moves required to 
// update the array such that each of 
// its element is divisible by K 
static void compute(int a[], int N, int K) 
      
    // Initialize Map data structure 
    Map<Long, 
        Long> eqVal = new HashMap<Long, 
                                Long>(); 
  
    long maxX = 0
  
    // Iterate for all the elements 
    // of the array 
    for(int i = 0; i < N; i++) 
    
          
        // Calculate the 
        // value to be added 
        long val = a[i] % K; 
  
        val = (val == 0 ? 0 : K - val); 
  
        // Check if the value equals 
        // to 0 then simply continue 
        if (val == 0
            continue
  
        // Check if the value to be 
        // added is present in the map 
        if (eqVal.containsKey(val)) 
        
            long numVal = eqVal.get(val); 
              
            // Update the answer 
            maxX = Math.max(maxX, 
                            val + (K * numVal)); 
  
            eqVal.put(val, 
            eqVal.getOrDefault(val, 0l) + 1l); 
        
        else
        
            eqVal.put(val, 1l); 
            maxX = Math.max(maxX, val); 
        
    
  
    // Print the required result 
    // We need to add 1 to maxX 
    // because we cant ignore the 
    // first move where initially X=0 
    // and we need to increase it by 1 
    // to make some changes in array 
    System.out.println(maxX == 0 ? 0 : maxX + 1); 
  
// Driver code 
public static void main(String[] args) 
    int K = 3
    int a[] = { 1, 2, 2, 18 }; 
    int N = a.length; 
      
    compute(a, N, K); 
  
// This code is contributed by offbeat 

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 implementation to find the 
# Minimum number of moves required to 
# update the array such that each of 
# its element is divisible by K 
from collections import defaultdict 
  
# Function to find the Minimum number 
# of moves required to update the 
# array such that each of its 
# element is divisible by K 
def compute(a, N, K): 
  
    # Initialize Map data structure 
    eqVal = defaultdict(int
  
    maxX = 0
  
    # Iterate for all the elements 
    # of the array 
    for i in range(N): 
  
        # Calculate the 
        # value to be added 
        val = a[i] %
  
        if (val != 0): 
            val = K - val 
  
        # Check if the value equals 
        # to 0 then simply continue 
        if (val == 0): 
            continue
  
        # Check if the value to be 
        # added is present in the map 
        if (val in eqVal): 
            numVal = eqVal[val] 
              
            # Update the answer 
            maxX = max(maxX, 
                    val + (K * numVal)) 
  
            eqVal[val] += 1
        else
            eqVal[val] += 1
            maxX = max(maxX, val) 
  
    # Print the required result 
    # We need to add 1 to maxX 
    # because we cant ignore the 
    # first move where initially X=0 
    # and we need to increase it by 1 
    # to make some changes in array 
    if maxX == 0
        print(0
    else
        print(maxX + 1
      
# Driver code 
if __name__ == "__main__"
  
    K = 3
    a = [ 1, 2, 2, 18
    N = len(a) 
      
    compute(a, N, K) 
  
# This code is contributed by chitranayal 

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# implementation to find the 
// minimum number of moves required to 
// update the array such that each of 
// its element is divisible by K 
using System;
using System.Collections.Generic; 
  
class GFG{
      
// Function to find the minimum 
// number of moves required to
// update the array such that each of
// its element is divisible by K
static void compute(int []a, int N, int K)
{
      
    // Initialize Map data structure
    Dictionary<long
               long> eqVal = new Dictionary<long,
                                            long>();
  
    long maxX = 0;
  
    // Iterate for all the elements
    // of the array
    for(int i = 0; i < N; i++)
    {
          
        // Calculate the
        // value to be added
        long val = a[i] % K;
  
        val = (val == 0 ? 0 : K - val);
  
        // Check if the value equals
        // to 0 then simply continue
        if (val == 0)
            continue;
  
        // Check if the value to be
        // added is present in the map
        if (eqVal.ContainsKey(val))
        {
            long numVal = eqVal[val];
              
            // Update the answer
            maxX = Math.Max(maxX, 
                            val + (K * numVal));
                      
            eqVal[val] = 1 + 
            eqVal.GetValueOrDefault(val, 0);
        }
        else
        {
            eqVal.Add(val, 1);
            maxX = Math.Max(maxX, val);
        }
    }
  
    // Print the required result
    // We need to add 1 to maxX
    // because we cant ignore the
    // first move where initially X=0
    // and we need to increase it by 1
    // to make some changes in array
    Console.Write(maxX == 0 ? 0 : maxX + 1);
}
  
// Driver code
public static void Main(string[] args)
{
    int K = 3;
    int []a = { 1, 2, 2, 18 };
    int N = a.Length;
      
    compute(a, N, K); 
}
}
  
// This code is contributed by rutvik_56

chevron_right


Output: 

5

Time Complexity: O(N)
 

competitive-programming-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : offbeat, chitranayal, rutvik_56