Length of smallest subarray to be removed to make sum of remaining elements divisible by K
Last Updated :
11 Jul, 2022
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++
#include <bits/stdc++.h>
using namespace std;
void removeSmallestSubarray( int arr[],
int n, int k)
{
int mod_arr[n];
int total_sum = 0;
for ( int i = 0; i < n; i++) {
mod_arr[i] = (arr[i] + k) % k;
total_sum += arr[i];
}
int target_remainder
= total_sum % k;
if (target_remainder == 0) {
cout << "0" ;
return ;
}
unordered_map< int , int > map1;
map1[0] = -1;
int curr_remainder = 0;
int res = INT_MAX;
for ( int i = 0; i < n; i++) {
curr_remainder = (curr_remainder
+ arr[i] + k)
% k;
map1[curr_remainder] = i;
int mod
= (curr_remainder
- target_remainder
+ k)
% k;
if (map1.find(mod) != map1.end())
res = min(res, i - map1[mod]);
}
if (res == INT_MAX || res == n) {
res = -1;
}
cout << res;
}
int main()
{
int arr[] = { 3, 1, 4, 2 };
int N = sizeof (arr) / sizeof (arr[0]);
int K = 6;
removeSmallestSubarray(arr, N, K);
return 0;
}
|
Java
import java.util.*;
class GFG{
static void removeSmallestSubarray( int arr[],
int n, int k)
{
int []mod_arr = new int [n];
int total_sum = 0 ;
for ( int i = 0 ; i < n; i++)
{
mod_arr[i] = (arr[i] +
k) % k;
total_sum += arr[i];
}
int target_remainder =
total_sum % k;
if (target_remainder == 0 )
{
System.out.print( "0" );
return ;
}
HashMap<Integer,
Integer> map1 =
new HashMap<>();
map1.put( 0 , - 1 );
int curr_remainder = 0 ;
int res = Integer.MAX_VALUE;
for ( int i = 0 ; i < n; i++)
{
curr_remainder = (curr_remainder +
arr[i] + k) % k;
map1.put(curr_remainder, i);
int mod = (curr_remainder -
target_remainder +
k) % k;
if (map1.containsKey(mod))
res = Math.min(res, i -
map1.get(mod));
}
if (res == Integer.MAX_VALUE ||
res == n)
{
res = - 1 ;
}
System.out.print(res);
}
public static void main(String[] args)
{
int arr[] = { 3 , 1 , 4 , 2 };
int N = arr.length;
int K = 6 ;
removeSmallestSubarray(arr, N, K);
}
}
|
Python3
import sys
def removeSmallestSubarray(arr, n, k):
mod_arr = [ 0 ] * n
total_sum = 0
for i in range (n) :
mod_arr[i] = (arr[i] + k) % k
total_sum + = arr[i]
target_remainder = total_sum % k
if (target_remainder = = 0 ):
print ( "0" )
return
map1 = {}
map1[ 0 ] = - 1
curr_remainder = 0
res = sys.maxsize
for i in range (n):
curr_remainder = (curr_remainder +
arr[i] + k) % k
map1[curr_remainder] = i
mod = (curr_remainder -
target_remainder + k) % k
if (mod in map1.keys()):
res = min (res, i - map1[mod])
if (res = = sys.maxsize or res = = n):
res = - 1
print (res)
arr = [ 3 , 1 , 4 , 2 ]
N = len (arr)
K = 6
removeSmallestSubarray(arr, N, K)
|
C#
using System;
using System.Collections.Generic;
class GFG{
static void removeSmallestSubarray( int []arr,
int n, int k)
{
int []mod_arr = new int [n];
int total_sum = 0;
for ( int i = 0; i < n; i++)
{
mod_arr[i] = (arr[i] + k) % k;
total_sum += arr[i];
}
int target_remainder = total_sum % k;
if (target_remainder == 0)
{
Console.Write( "0" );
return ;
}
Dictionary< int ,
int > map1 = new Dictionary< int ,
int >();
map1.Add(0, -1);
int curr_remainder = 0;
int res = int .MaxValue;
for ( int i = 0; i < n; i++)
{
curr_remainder = (curr_remainder +
arr[i] + k) % k;
map1[curr_remainder] = i;
int mod = (curr_remainder -
target_remainder +
k) % k;
if (map1.ContainsKey(mod))
res = Math.Min(res, i -
map1[mod]);
}
if (res == int .MaxValue ||
res == n)
{
res = -1;
}
Console.Write(res);
}
public static void Main(String[] args)
{
int []arr = { 3, 1, 4, 2 };
int N = arr.Length;
int K = 6;
removeSmallestSubarray(arr, N, K);
}
}
|
Javascript
<script>
function removeSmallestSubarray(arr, n, k) {
let mod_arr = new Array(n);
let total_sum = 0;
for (let i = 0; i < n; i++) {
mod_arr[i] = (arr[i] + k) % k;
total_sum += arr[i];
}
let target_remainder
= total_sum % k;
if (target_remainder == 0) {
document.write( "0" );
return ;
}
let map1 = new Map();
map1.set(0, -1);
let curr_remainder = 0;
let res = Number.MAX_SAFE_INTEGER;
for (let i = 0; i < n; i++) {
curr_remainder = (curr_remainder
+ arr[i] + k)
% k;
map1.set(curr_remainder, i);
let mod
= (curr_remainder
- target_remainder
+ k)
% k;
if (map1.has(mod))
res = Math.min(res, i - map1.get(mod));
}
if (res == Number.MAX_SAFE_INTEGER || res == n) {
res = -1;
}
document.write(res);
}
let arr = [3, 1, 4, 2];
let N = arr.length;
let K = 6;
removeSmallestSubarray(arr, N, K);
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(N)
Related Topic: Subarrays, Subsequences, and Subsets in Array
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...