Skip to content
Related Articles

Related Articles

Improve Article
Length of smallest subarray to be removed to make sum of remaining elements divisible by K
  • Difficulty Level : Hard
  • Last Updated : 18 Jun, 2021

Given an array arr[] of integers and an integer K, the task is to find the length of the smallest subarray that needs to be removed such that the sum of remaining array elements is divisible by K. Removal of the entire array is not allowed. If it is impossible, then print “-1”.

Examples:

Input: arr[] = {3, 1, 4, 2}, K = 6
Output: 1
Explanation: Sum of array elements = 10, which is not divisible by 6. After removing the subarray {4}, sum of the remaining elements is 6. Therefore, the length of the removed subarray is 1.

Input: arr[] = {3, 6, 7, 1}, K = 9
Output: 2
Explanation: Sum of array elements = 17, which is not divisible by 9. After removing the subarray {7, 1} and the, sum of the remaining elements is 9. Therefore, the length of the removed subarray is 2.

Naive Approach: The simplest approach is to generate all possible subarray from the given array arr[] excluding the subarray of length N. Now, find the minimum length of subarray such that the difference between the sum of all the elements of the array and the sum of the elements in that subarray is divisible by K. If no such subarray exists, then print “-1”



Time Complexity: O(N2)
Auxiliary Space: O(1)

Efficient Approach: To optimize the above approach, the idea is based on the below observation:

((total_sum – subarray_sum) % K + subarray_sum % K) must be equal to total_sum % K.
But, (total_sum – subarray_sum) % K == 0 should be true.

Therefore, total_sum % K == subarray_sum % K, so both subarray_sum and total_sum should leave the same remainder when divided by K. Hence, the task is to find the length of the smallest subarray whose sum of elements will leave a remainder of (total_sum % K).

Follow the steps below to solve this problem:

  • Initialize variable res as INT_MAX to store the minimum length of the subarray to be removed.
  • Calculate total_sum and the remainder which it leaves when divided by K.
  • Create an auxiliary array modArr[] to storing the remainder of each arr[i] when it is divided by K as:

modArr[i] = (arr[i] + K) % K.
where, 
K has been added while calculating the remainder to handle the case of negative integers.

  • Traverse the given array and maintain an unordered_map to stores the recent position of the remainder encountered and keep track of the minimum required subarray having the remainder same as the target_remainder.
  • If there exists any key in the map which is equal to (curr_remainder – target_remainder + K) % K, then store that subarray length in variable res as the minimum of res and current length found.
  • After the above, if res is unchanged the print “-1” Otherwise print the value of res.

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 length of the
// smallest subarray to be removed such
// that sum of elements is divisible by K
void removeSmallestSubarray(int arr[],
                            int n, int k)
{
    // Stores the remainder of each
    // arr[i] when divided by K
    int mod_arr[n];
 
    // Stores total sum of elements
    int total_sum = 0;
 
    // K has been added to each arr[i]
    // to handle -ve integers
    for (int i = 0; i < n; i++) {
        mod_arr[i] = (arr[i] + k) % k;
 
        // Update the total sum
        total_sum += arr[i];
    }
 
    // Remainder when total_sum
    // is divided by K
    int target_remainder
        = total_sum % k;
 
    // If given array is already
    // divisible by K
    if (target_remainder == 0) {
        cout << "0";
        return;
    }
 
    // Stores curr_remainder and the
    // most recent index at which
    // curr_remainder has occured
    unordered_map<int, int> map1;
    map1[0] = -1;
 
    int curr_remainder = 0;
 
    // Stores required answer
    int res = INT_MAX;
 
    for (int i = 0; i < n; i++) {
 
        // Add current element to
        // curr_sum and take mod
        curr_remainder = (curr_remainder
                          + arr[i] + k)
                         % k;
 
        // Update current remainder index
        map1[curr_remainder] = i;
 
        int mod
            = (curr_remainder
               - target_remainder
               + k)
              % k;
 
        // If mod already exists in map
        // the subarray exists
        if (map1.find(mod) != map1.end())
            res = min(res, i - map1[mod]);
    }
 
    // If not possible
    if (res == INT_MAX || res == n) {
        res = -1;
    }
 
    // Print the result
    cout << res;
}
 
// Driver Code
int main()
{
    // Given array arr[]
    int arr[] = { 3, 1, 4, 2 };
 
    // Size of array
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Given K
    int K = 6;
 
    // Function Call
    removeSmallestSubarray(arr, N, K);
 
    return 0;
}

Java




// Java program for the
// above approach
import java.util.*;
class GFG{
 
// Function to find the length of the
// smallest subarray to be removed such
// that sum of elements is divisible by K
static void removeSmallestSubarray(int arr[],
                                   int n, int k)
{
  // Stores the remainder of each
  // arr[i] when divided by K
  int []mod_arr = new int[n];
 
  // Stores total sum of
  // elements
  int total_sum = 0;
 
  // K has been added to each
  // arr[i] to handle -ve integers
  for (int i = 0; i < n; i++)
  {
    mod_arr[i] = (arr[i] +
                  k) % k;
 
    // Update the total sum
    total_sum += arr[i];
  }
 
  // Remainder when total_sum
  // is divided by K
  int target_remainder =
      total_sum % k;
 
  // If given array is already
  // divisible by K
  if (target_remainder == 0)
  {
    System.out.print("0");
    return;
  }
 
  // Stores curr_remainder and the
  // most recent index at which
  // curr_remainder has occured
  HashMap<Integer,
          Integer> map1 =
          new HashMap<>();
  map1.put(0, -1);
 
  int curr_remainder = 0;
 
  // Stores required answer
  int res = Integer.MAX_VALUE;
 
  for (int i = 0; i < n; i++)
  {
    // Add current element to
    // curr_sum and take mod
    curr_remainder = (curr_remainder +
                      arr[i] + k) % k;
 
    // Update current remainder
    // index
    map1.put(curr_remainder, i);
 
    int mod = (curr_remainder -
               target_remainder +
               k) % k;
 
    // If mod already exists in
    // map the subarray exists
    if (map1.containsKey(mod))
      res = Math.min(res, i -
                     map1.get(mod));
  }
 
  // If not possible
  if (res == Integer.MAX_VALUE ||
      res == n)
  {
    res = -1;
  }
 
  // Print the result
  System.out.print(res);
}
 
// Driver Code
public static void main(String[] args)
{
  // Given array arr[]
  int arr[] = {3, 1, 4, 2};
 
  // Size of array
  int N = arr.length;
 
  // Given K
  int K = 6;
 
  // Function Call
  removeSmallestSubarray(arr, N, K);
}
}
 
// This code is contributed by gauravrajput1

Python3




# Python3 program for the above approach
import sys
 
# Function to find the length of the
# smallest subarray to be removed such
# that sum of elements is divisible by K
def removeSmallestSubarray(arr, n, k):
     
    # Stores the remainder of each
    # arr[i] when divided by K
    mod_arr = [0] * n
  
    # Stores total sum of elements
    total_sum = 0
  
    # K has been added to each arr[i]
    # to handle -ve integers
    for i in range(n) :
        mod_arr[i] = (arr[i] + k) % k
  
        # Update the total sum
        total_sum += arr[i]
         
    # Remainder when total_sum
    # is divided by K
    target_remainder = total_sum % k
  
    # If given array is already
    # divisible by K
    if (target_remainder == 0):
        print("0")
        return
     
    # Stores curr_remainder and the
    # most recent index at which
    # curr_remainder has occured
    map1 = {}
    map1[0] = -1
  
    curr_remainder = 0
  
    # Stores required answer
    res = sys.maxsize
  
    for i in range(n):
         
        # Add current element to
        # curr_sum and take mod
        curr_remainder = (curr_remainder +
                             arr[i] + k) % k
  
        # Update current remainder index
        map1[curr_remainder] = i
  
        mod = (curr_remainder -
             target_remainder + k) % k
  
        # If mod already exists in map
        # the subarray exists
        if (mod in map1.keys()):
            res = min(res, i - map1[mod])
     
    # If not possible
    if (res == sys.maxsize or res == n):
        res = -1
     
    # Print the result
    print(res)
 
# Driver Code
 
# Given array arr[]
arr = [ 3, 1, 4, 2 ]
  
# Size of array
N = len(arr)
  
# Given K
K = 6
  
# Function Call
removeSmallestSubarray(arr, N, K)
 
# This code is contributed by susmitakundugoaldanga

C#




// C# program for the
// above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function to find the length of the
// smallest subarray to be removed such
// that sum of elements is divisible by K
static void removeSmallestSubarray(int []arr,
                                   int n, int k)
{
   
  // Stores the remainder of each
  // arr[i] when divided by K
  int []mod_arr = new int[n];
 
  // Stores total sum of
  // elements
  int total_sum = 0;
 
  // K has been added to each
  // arr[i] to handle -ve integers
  for(int i = 0; i < n; i++)
  {
    mod_arr[i] = (arr[i] + k) % k;
 
    // Update the total sum
    total_sum += arr[i];
  }
 
  // Remainder when total_sum
  // is divided by K
  int target_remainder = total_sum % k;
 
  // If given array is already
  // divisible by K
  if (target_remainder == 0)
  {
    Console.Write("0");
    return;
  }
 
  // Stores curr_remainder and the
  // most recent index at which
  // curr_remainder has occured
  Dictionary<int,
             int> map1 = new Dictionary<int,
                                        int>();
   
  map1.Add(0, -1);
 
  int curr_remainder = 0;
 
  // Stores required answer
  int res = int.MaxValue;
 
  for(int i = 0; i < n; i++)
  {
     
    // Add current element to
    // curr_sum and take mod
    curr_remainder = (curr_remainder +
                      arr[i] + k) % k;
 
    // Update current remainder
    // index
    map1[curr_remainder] = i;
 
    int mod = (curr_remainder -
               target_remainder +
               k) % k;
 
    // If mod already exists in
    // map the subarray exists
    if (map1.ContainsKey(mod))
      res = Math.Min(res, i -
                     map1[mod]);
  }
 
  // If not possible
  if (res == int.MaxValue ||
      res == n)
  {
    res = -1;
  }
   
  // Print the result
  Console.Write(res);
}
 
// Driver Code
public static void Main(String[] args)
{
   
  // Given array []arr
  int []arr = { 3, 1, 4, 2 };
 
  // Size of array
  int N = arr.Length;
 
  // Given K
  int K = 6;
 
  // Function Call
  removeSmallestSubarray(arr, N, K);
}
}
 
// This code is contributed by 29AjayKumar

Javascript




<script>
 
// JavaScript program for the above approach
 
// Function to find the length of the
// smallest subarray to be removed such
// that sum of elements is divisible by K
function removeSmallestSubarray(arr, n, k) {
    // Stores the remainder of each
    // arr[i] when divided by K
    let mod_arr = new Array(n);
 
    // Stores total sum of elements
    let total_sum = 0;
 
    // K has been added to each arr[i]
    // to handle -ve integers
    for (let i = 0; i < n; i++) {
        mod_arr[i] = (arr[i] + k) % k;
 
        // Update the total sum
        total_sum += arr[i];
    }
 
    // Remainder when total_sum
    // is divided by K
    let target_remainder
        = total_sum % k;
 
    // If given array is already
    // divisible by K
    if (target_remainder == 0) {
        document.write("0");
        return;
    }
 
    // Stores curr_remainder and the
    // most recent index at which
    // curr_remainder has occured
    let map1 = new Map();
    map1.set(0, -1);
 
    let curr_remainder = 0;
 
    // Stores required answer
    let res = Number.MAX_SAFE_INTEGER;
 
    for (let i = 0; i < n; i++) {
 
        // Add current element to
        // curr_sum and take mod
        curr_remainder = (curr_remainder
            + arr[i] + k)
            % k;
 
        // Update current remainder index
        map1.set(curr_remainder, i);
 
        let mod
            = (curr_remainder
                - target_remainder
                + k)
            % k;
 
        // If mod already exists in map
        // the subarray exists
        if (map1.has(mod))
            res = Math.min(res, i - map1.get(mod));
    }
 
    // If not possible
    if (res == Number.MAX_SAFE_INTEGER || res == n) {
        res = -1;
    }
 
    // Print the result
    document.write(res);
}
 
// Driver Code
 
// Given array arr[]
let arr = [3, 1, 4, 2];
 
// Size of array
let N = arr.length;
 
// Given K
let K = 6;
 
// Function Call
removeSmallestSubarray(arr, N, K);
 
</script>
Output: 
1

 

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

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with industry experts, please refer DSA Live Classes




My Personal Notes arrow_drop_up
Recommended Articles
Page :