Length of smallest subarray to be removed to make sum of remaining elements divisible by K
Last Updated :
23 Jul, 2025
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
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem