Open In App

Minimum count of groups such that sum of adjacent elements is divisible by K in each group

Last Updated : 28 Jul, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array arr[] consisting of N integers, and an integer K, the task is to print the minimum count of groups formed by taking elements of the array such that the sum of adjacent elements is divisible by K in each group.

Examples:

Input: arr[] = {2, 6, 5, 8, 2, 9}, K = 2
Output: 2
The array can be split into two groups {2, 6, 2, 8} and {5, 9}.
The sum of adjacent elements of each group is divisible by K.
Thus, the minimum number of groups that can be formed is 2.

Input: arr[] = {1, 1, 4, 4, 8, 6, 7}, K = 8
Output: 4
Explanation:
The array can be split into 4 groups: {1, 7, 1}, {4, 4}, {8}, and {6}.
The sum of adjacent elements of each group is divisible by K.
Thus, the minimum number of groups that can be formed is 4.

Input: arr[] = {144}, K = 5
Output: 1

Approach: The given problem can be solved based on the following observations: 

  • It can be observed that a group should be formed as:
    1. Groups should consist of only one element which is not divisible by K.
    2. All elements of the groups should be individually divisible by K.
    3. Every adjacent element of the group should be satisfied; X % K + Y % K = K, where X and Y are two adjacent elements of the group.

Follow the steps below to solve the problem:

  • Initialize a map<int, int>, say mp, to store the count of arr[i] % K.
  • Initialize a variable, say ans as 0, to store the count of groups.
  • Traverse the array arr[] and increment the count of arr[i] % K in the mp and if arr[i] % K is 0 then assign 1 to ans.
  • Iterate over the range [1, K / 2] and perform the following operations:
    • Store the minimum of mp[i] and mp[K – i] in a variable, say C1.
    • Store the maximum of mp[i] and mp[K – i] in a variable, say C2.
    • If C1 is 0 then increment ans by C2.
    • Otherwise, if C1 is either equal to C1 or C1 + 1, then increment ans by 1.
    • Otherwise, increment ans by C2 – C1 – 1.
  • Finally, after completing the above steps, print the answer obtained in ans.

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 the minimum number
// of groups
int findMinGroups(int arr[], int N, int K)
{
    // Stores the count of elements
    unordered_map<int, int> mp;
 
    // Stores the count of groups
    int ans = 0;
 
    // Traverse the array arr[]
    for (int i = 0; i < N; i++) {
 
        // Update arr[i]
        arr[i] = arr[i] % K;
 
        // If arr[i] is 0
        if (arr[i] == 0) {
 
            // Update ans
            ans = 1;
        }
        else {
 
            // Increment mp[arr[i]] by 1
            mp[arr[i]]++;
        }
    }
 
    // Iterarte over the range [1, K / 2]
    for (int i = 1; i <= K / 2; i++) {
 
        // Stores the minimum of count of i
        // and K - i
        int c1 = min(mp[K - i], mp[i]);
 
        // Stores the maximum of count of i
        // and K - i
        int c2 = max(mp[K - i], mp[i]);
 
        // If c1 is 0
        if (c1 == 0) {
 
            // Increment ans by c2
            ans += c2;
        }
 
        // Otherwise if c2 is equal to c1 + 1
        // or c1
        else if (c2 == c1 + 1 || c1 == c2) {
 
            // Increment ans by 1
            ans++;
        }
        // Otherwise
        else {
 
            // Increment ans by c2 - c1 - 1
            ans += (c2 - c1 - 1);
        }
    }
 
    // Return the ans
    return ans;
}
 
// Driver Code
int main()
{
    // Input
    int arr[] = { 1, 1, 4, 4, 8, 6, 7 };
    int N = sizeof(arr) / sizeof(arr[0]);
    int K = 8;
 
    // Function Call
    cout << findMinGroups(arr, N, K);
 
    return 0;
}


Java




// Java program for the above approach
import java.io.*;
import java.util.*;
 
class GFG
{
   
    // Function to count the minimum number
    // of groups
    public static int findMinGroups(int arr[], int N, int K)
    {
        // Stores the count of elements
        HashMap<Integer, Integer> mp = new HashMap<>();
         
        // Stores the count of groups
        int ans = 0;
     
        // Traverse the array arr[]
        for (int i = 0; i < N; i++) {
     
            // Update arr[i]
            arr[i] = arr[i] % K;
     
            // If arr[i] is 0
            if (arr[i] == 0) {
     
                // Update ans
                ans = 1;
            }
            else {
     
                // Increment mp[arr[i]] by 1
                if (!mp.containsKey(arr[i])) {
                    mp.put(arr[i], 1);
                }
                else {
                    Integer ct = mp.get(arr[i]);
                    if(ct!=null)
                    {
                        ct++;
                        mp.put(arr[i], ct);
                    }
                }
            }
        }
     
        // Iterarte over the range [1, K / 2]
        for (int i = 1; i <= K / 2; i++) {
     
            // Stores the minimum of count of i
            // and K - i
            int a=0,b=0;
            if(mp.containsKey(K-i)){
                a=mp.get(K-i);
            }
            if(mp.containsKey(i)){
                b=mp.get(i);
            }
            int c1 = Math.min(a, b);
     
            // Stores the maximum of count of i
            // and K - i
            int c2 = Math.max(a, b);
     
            // If c1 is 0
            if (c1 == 0) {
     
                // Increment ans by c2
                ans += c2;
            }
     
            // Otherwise if c2 is equal to c1 + 1
            // or c1
            else if (c2 == c1 + 1 || c1 == c2) {
     
                // Increment ans by 1
                ans++;
            }
            // Otherwise
            else {
     
                // Increment ans by c2 - c1 - 1
                ans += (c2 - c1 - 1);
            }
        }
     
        // Return the ans
        return ans;
    }
    public static void main (String[] args) {
        // Input
        int arr[] = { 1, 1, 4, 4, 8, 6, 7 };
        int N = 7;
        int K = 8;
         
        // Function Call
        System.out.println(findMinGroups(arr, N, K));
    }
}
 
// This code is contributed by Manu Pathria


Python3




# Python3 program for the above approach
 
# Function to count the minimum number
# of groups
def findMinGroups(arr, N, K):
     
    # Stores the count of elements
    mp = {}
 
    # Stores the count of groups
    ans = 0
 
    # Traverse the array arr[]
    for i in range(N):
         
        # Update arr[i]
        arr[i] = arr[i] % K
 
        # If arr[i] is 0
        if (arr[i] == 0):
             
            # Update ans
            ans = 1
        else:
            mp[arr[i]] = mp.get(arr[i], 0) + 1
 
    # Iterarte over the range [1, K / 2]
    for i in range(1, K // 2):
         
        # Stores the minimum of count of i
        # and K - i
        x, y = (0 if (K - i) not in mp else mp[K - i],
                      0 if i not in mp else mp[K - i])
        c1 = min(x, y)
 
        # The maximum of count of i
        # K - i
        c2 = max(x, y)
 
        # If c1 is 0
        if (c1 == 0):
             
            # Increment ans by c2
            ans += c2
             
        # Otherwise if c2 is equal to c1 + 1
        # or c1
        elif (c2 == c1 + 1 or c1 == c2):
             
            # Increment ans by 1
            ans += 1
             
        # Otherwise   
        else:
 
            # Increment ans by c2 - c1 - 1
            ans += (c2 - c1 - 1)
             
    # Return the ans
    return ans + 1
 
# Driver code
if __name__ == '__main__':
     
    # Input
    arr = [ 1, 1, 4, 4, 8, 6, 7 ]
    N = len(arr)
    K = 8
 
    # Function Call
    print(findMinGroups(arr, N, K))
 
# This code is contributed by mohit kumar 29


C#




// C# program for the above approach
using System;
using System.Collections.Generic;
 
public class GFG{
 
    // Function to count the minimum number
    // of groups
     static int findMinGroups(int[] arr, int N, int K)
    {
        // Stores the count of elements
        Dictionary<int, int> mp = new Dictionary<int, int>();
         
        // Stores the count of groups
        int ans = 0;
     
        // Traverse the array arr[]
        for (int i = 0; i < N; i++) {
     
            // Update arr[i]
            arr[i] = arr[i] % K;
     
            // If arr[i] is 0
            if (arr[i] == 0) {
     
                // Update ans
                ans = 1;
            }
            else {
     
                // Increment mp[arr[i]] by 1
                if (!mp.ContainsKey(arr[i])) {
                    mp.Add(arr[i], 1);
                }
                else {
                    int ct = mp[arr[i]];
                    if(ct!=0)
                    {
                        ct++;
                        mp[arr[i]]= ct;
                    }
                }
            }
        }
     
        // Iterarte over the range [1, K / 2]
        for (int i = 1; i <= K / 2; i++) {
     
            // Stores the minimum of count of i
            // and K - i
            int a=0,b=0;
            if(mp.ContainsKey(K-i)){
                a=mp[K-i];
            }
            if(mp.ContainsKey(i)){
                b=mp[i];
            }
            int c1 = Math.Min(a, b);
     
            // Stores the maximum of count of i
            // and K - i
            int c2 = Math.Max(a, b);
     
            // If c1 is 0
            if (c1 == 0) {
     
                // Increment ans by c2
                ans += c2;
            }
     
            // Otherwise if c2 is equal to c1 + 1
            // or c1
            else if (c2 == c1 + 1 || c1 == c2) {
     
                // Increment ans by 1
                ans++;
            }
            // Otherwise
            else {
     
                // Increment ans by c2 - c1 - 1
                ans += (c2 - c1 - 1);
            }
        }
     
        // Return the ans
        return ans;
    }
    static public void Main ()
    {
        // InAdd
        int[] arr = { 1, 1, 4, 4, 8, 6, 7 };
        int N = 7;
        int K = 8;
         
        // Function Call
        Console.Write(findMinGroups(arr, N, K));
    }
}
 
// This code is contributed by shubhamsingh10


Javascript




<script>
       // JavaScript program for the above approach
 
       // Function to count the minimum number
       // of groups
       function findMinGroups(arr, N, K)
       {
        
           // Stores the count of elements
           let mp = new Map();
 
           // Stores the count of groups
           let ans = 0;
 
           // Traverse the array arr[]
           for (let i = 0; i < N; i++) {
 
               // Update arr[i]
               arr[i] = arr[i] % K;
 
               // If arr[i] is 0
               if (arr[i] == 0) {
 
                   // Update ans
                   ans = 1;
               }
               else {
 
                   // Increment mp[arr[i]] by 1
                   if (!mp.has(arr[i])) {
                       mp.set(arr[i], 1);
                   }
                   else {
                       let ct = mp.get(arr[i]);
                       if (ct != null) {
                           ct++;
                           mp.set(arr[i], ct);
                       }
                   }
               }
           }
 
           // Iterarte over the range [1, K / 2]
           for (let i = 1; i <= K / 2; i++) {
 
               // Stores the minimum of count of i
               // and K - i
               let a = 0, b = 0;
               if (mp.has(K - i)) {
                   a = mp.get(K - i);
               }
               if (mp.has(i)) {
                   b = mp.get(i);
               }
               let c1 = Math.min(a, b);
 
               // Stores the maximum of count of i
               // and K - i
               let c2 = Math.max(a, b);
 
               // If c1 is 0
               if (c1 == 0) {
 
                   // Increment ans by c2
                   ans += c2;
               }
 
               // Otherwise if c2 is equal to c1 + 1
               // or c1
               else if (c2 == c1 + 1 || c1 == c2) {
 
                   // Increment ans by 1
                   ans++;
               }
               // Otherwise
               else {
 
                   // Increment ans by c2 - c1 - 1
                   ans += (c2 - c1 - 1);
               }
           }
 
           // Return the ans
           return ans;
       }
 
       // Input
       let arr = [1, 1, 4, 4, 8, 6, 7];
       let N = 7;
       let K = 8;
 
       // Function Call
       document.write(findMinGroups(arr, N, K));
 
   // This code is contributed by Potta Lokesh
 
   </script>


Output

4

Time Complexity: O(N)
Auxiliary Space: O(K)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads