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++
// 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 occurred
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 occurred
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 occurred
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 occurred
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 occurred
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>
Time Complexity: O(N)
Auxiliary Space: O(N)
Related Topic: Subarrays, Subsequences, and Subsets in Array
Similar Reads
Length of smallest subarray required to be removed to make remaining elements consecutive
Given an array arr[] consisting of N integers, the task is to find the length of the smallest subarray required to be removed to make the remaining array elements consecutive. Examples: Input: arr[] = {1, 2, 3, 7, 5, 4, 5}Output: 2Explanation:Removing the subarray {7, 5} from the array arr[] modifie
15+ min read
Find the index of the smallest element to be removed to make sum of array divisible by K
Given an array arr[] of size N and a positive integer K, the task is to find the index of the smallest array element required to be removed to make the sum of remaining array divisible by K. If multiple solutions exist, then print the smallest index. Otherwise, print -1. Examples: Input: arr[ ] = {6
8 min read
Smallest submatrix required to be removed such that sum of the remaining matrix is divisible by K
Given a 2D matrix mat[][] of size N * M and a positive integer K, the task is to find the area of the smallest rectangular submatrix that is required to be removed such that the sum of the remaining elements in the matrix is divisible by K. Examples: Input: mat[][] = { {6, 2, 6}, {3, 2, 8}, {2, 5, 3
15+ min read
Length of the Smallest Subarray that must be removed in order to Maximise the GCD
Given an array arr[] of N elements, the task is to find the length of the smallest subarray such that when this subarray is removed from the array, the GCD of the resultant array is maximum. Note: The resulting array should be non-empty.Examples: Input: N = 4, arr[] = {3, 6, 1, 2} Output: 2 Explanat
7 min read
Size of smallest subarray to be removed to make count of array elements greater and smaller than K equal
Given an integer K and an array arr[] consisting of N integers, the task is to find the length of the subarray of smallest possible length to be removed such that the count of array elements smaller than and greater than K in the remaining array are equal. Examples: Input: arr[] = {5, 7, 2, 8, 7, 4,
10 min read
Print indices of pair of array elements required to be removed to split array into 3 equal sum subarrays
Given an array arr[] consisting of N integers, the task is to print the indices of two array elements required to be removed such that the given array can be split into three subarrays of equal sum. If not possible to do so, then print "-1". Examples: Input: arr[] = {2, 5, 12, 7, 19, 4, 3}Output: 2
15+ min read
Minimum number of elements to be removed such that the sum of the remaining elements is equal to k
Given an array arr[] of integers and an integer k, the task is to find the minimum number of integers that need to be removed from the array such that the sum of the remaining elements is equal to k. If we cannot get the required sum the print -1.Examples: Input: arr[] = {1, 2, 3}, k = 3 Output: 1 E
8 min read
Count subarrays such that remainder after dividing sum of elements by K gives count of elements
Given an array arr[] of size N and an element K. The task is to find the number of sub-arrays of the given array such that the remainder when dividing the sum of its elements by K is equal to the number of elements in the subarray. Examples: Input: arr[] = {1, 4, 2, 3, 5}, K = 4 Output: 4 {1}, {1, 4
9 min read
Longest subarray with elements divisible by k
Suppose you are given an array. You have to find the length of the longest subarray such that each and every element of it is divisible by k.Examples: Input : arr[] = { 1, 7, 2, 6, 8, 100, 3, 6, 16}, k=2Output : 4 Input : arr[] = { 3, 11, 22, 32, 55, 100, 1, 5}, k=5Output : 2 Approach: Initialize tw
4 min read
Length of smallest Subarray with at least one element repeated K times
Given an array arr[] of length N and an integer K. The task is to find the minimum length of subarray such that at least one element of the subarray is repeated exactly K times in that subarray. If no such subarray exists, print -1. Examples: Input: arr[] = {1, 2, 1, 2, 1}, K = 2Output: 3Explanation
9 min read