Subarray with no pair sum divisible by K
Last Updated :
11 Jul, 2025
Given an array of N non-negative integers, task is to find the maximum size of a subarray such that the pairwise sum of the elements of this subarray is not divisible by a given integer, K. Also, print this subarray as well. If there are two or more subarrays that follow the above stated condition, then print the first one from the left.
Prerequisite : Subset with no pair sum divisible by K
Examples :
Input : arr[] = [3, 7, 1, 9, 2]
K = 3
Output : 3
[3, 7, 1]
3 + 7 = 10, 3 + 1 = 4, 7 + 1 = 8, all are
not divisible by 3.
It is not possible to get a subarray of size bigger
than 3 with the above-mentioned property.
[7, 1, 9] is also of the same size but [3, 7, 1] comes first.
Input : arr[] = [2, 4, 4, 3]
K = 4
Output : 2
[2, 4]
2 + 4 = 6 is not divisible by 4.
It is not possible to get a subarray of size bigger
than 2 with the above-mentioned property.
[4, 3] is also of the same size but [2, 4] comes first.
Naive Approach: The naive method would be to consider all the subarrays. While considering a subarray, take elements pairwise and compute the sum of the two elements of the pair. If the computed sum is divisible by K, then ignore this subarray and continue with the next subarray. Else, compute the sum of other pairs of this subarray in a similar fashion. If no pair's sum is a multiple of K, then compare the size of this subarray with the maximum size obtained so far and update if required.
The time complexity of this method would be O(n^4 ).
Efficient Approach(Using Hashing): We create an empty hash table and insert arr[0] % k into it. Now we traverse remaining elements and maintain a window such that no pair in the window is divisible by k. For every traversed element, we remove starting elements while there exist an element in current window which makes a divisible pair with current element. To check if there is an element in current window, we check if following.
- If there is an element x such that (K - x % K) is equal to arr[i] % K
- OR arr[i] % k is 0 and it exists in the hash.
Once we make sure that all elements which can make a pair with arr[i] are removed, we add arr[i] to current window and check if size of current window is more than the maximum window so far.
Steps to solve this problem:
1. declare a map mp of int key and value.
2. declare variable s=0,e=0,maxs=0,maxe=0.
3. insert mp[arr[0]%k]++.
4. iterate through i=1 till n:
* declare variable mod=arr[i]%k.
* while mp[k-mod] is not equal to zero or mod==0 and mp[mod] is not equal to zero:
* update mp[arr[s]%k]--.
* increment s.
*update mp[mod]++.
*increment e.
*check if ((e-s)>(maxe-maxs)) than update maxe and maxs to e and s.
5. iterating i=maxs till maxe:
* print arr[i].
Implementation:
C++
// CPP code to find the subarray with
// no pair sum divisible by K
#include<bits/stdc++.h>
using namespace std;
// function to find the subarray with
// no pair sum divisible by k
void subarrayDivisibleByK(int arr[], int n, int k)
{
// hash table to store the remainders
// obtained on dividing by K
map<int,int> mp;
// s : starting index of the
// current subarray, e : ending
// index of the current subarray, maxs :
// starting index of the maximum
// size subarray so far, maxe : ending
// index of the maximum size subarray
// so far
int s = 0, e = 0, maxs = 0, maxe = 0;
// insert the first element in the set
mp[arr[0] % k]++;
for (int i = 1; i < n; i++)
{
int mod = arr[i] % k;
// Removing starting elements of current
// subarray while there is an element in
// set which makes a pair with mod[i] such
// that the pair sum is divisible.
while (mp[k - mod] != 0 ||
(mod == 0 && mp[mod] != 0))
{
mp[arr[s] % k]--;
s++;
}
// include the current element in
// the current subarray the ending
// index of the current subarray
// increments by one
mp[mod]++;
e++;
// compare the size of the current
// subarray with the maximum size so
// far
if ((e - s) > (maxe - maxs))
{
maxe = e;
maxs = s;
}
}
cout << "The maximum size is "
<< maxe - maxs + 1 << " and "
"the subarray is as follows\n";
for (int i=maxs; i<=maxe; i++)
cout << arr[i] << " ";
}
int main()
{
int k = 3;
int arr[] = {5, 10, 15, 20, 25};
int n = sizeof(arr)/sizeof(arr[0]);
subarrayDivisibleByK(arr, n, k);
return 0;
}
Java
// Java Program to find the subarray with
// no pair sum divisible by K
import java.io.*;
import java.util.*;
public class GFG {
// function to find the subarray with
// no pair sum divisible by k
static void subarrayDivisibleByK(int []arr,
int n, int k)
{
// hash table to store the remainders
// obtained on dividing by K
int []mp = new int[1000];
// s : starting index of the
// current subarray, e : ending
// index of the current subarray, maxs :
// starting index of the maximum
// size subarray so far, maxe : ending
// index of the maximum size subarray
// so far
int s = 0, e = 0, maxs = 0, maxe = 0;
// insert the first element in the set
mp[arr[0] % k]++;
for (int i = 1; i < n; i++)
{
int mod = arr[i] % k;
// Removing starting elements of current
// subarray while there is an element in
// set which makes a pair with mod[i] such
// that the pair sum is divisible.
while (mp[k - mod] != 0 ||
(mod == 0 && mp[mod] != 0))
{
mp[arr[s] % k]--;
s++;
}
// include the current element in
// the current subarray the ending
// index of the current subarray
// increments by one
mp[mod]++;
e++;
// compare the size of the current
// subarray with the maximum size so
// far
if ((e - s) > (maxe - maxs))
{
maxe = e;
maxs = s;
}
}
System.out.print("The maximum size is "
+ (maxe - maxs + 1)
+ " and the subarray is as follows\n");
for (int i = maxs; i <= maxe; i++)
System.out.print(arr[i] + " ");
}
// Driver Code
public static void main(String args[])
{
int k = 3;
int []arr = {5, 10, 15, 20, 25};
int n = arr.length;
subarrayDivisibleByK(arr, n, k);
}
}
// This code is contributed by
// Manish Shaw (manishshaw1)
Python3
# Python3 Program to find the subarray with
# no pair sum divisible by K
# function to find the subarray with
# no pair sum divisible by k
def subarrayDivisibleByK(arr, n, k) :
# hash table to store the remainders
# obtained on dividing by K
mp = [0] * 1000
# s : starting index of the
# current subarray, e : ending
# index of the current subarray, maxs :
# starting index of the maximum
# size subarray so far, maxe : ending
# index of the maximum size subarray
# so far
s = 0; e = 0; maxs = 0; maxe = 0;
# insert the first element in the set
mp[arr[0] % k] = mp[arr[0] % k] + 1;
for i in range(1, n):
mod = arr[i] % k
# Removing starting elements of current
# subarray while there is an element in
# set which makes a pair with mod[i] such
# that the pair sum is divisible.
while (mp[k - mod] != 0 or (mod == 0
and mp[mod] != 0)) :
mp[arr[s] % k] = mp[arr[s] % k] - 1
s = s + 1
# include the current element in
# the current subarray the ending
# index of the current subarray
# increments by one
mp[mod] = mp[mod] + 1
e = e + 1
# compare the size of the current
# subarray with the maximum size so
# far
if ((e - s) > (maxe - maxs)) :
maxe = e
maxs = s
print ("The maximum size is {} and the "
" subarray is as follows"
.format((maxe - maxs + 1)))
for i in range(maxs, maxe + 1) :
print ("{} ".format(arr[i]), end="")
# Driver Code
k = 3
arr = [5, 10, 15, 20, 25]
n = len(arr)
subarrayDivisibleByK(arr, n, k)
# This code is contributed by
# Manish Shaw (manishshaw1)
C#
// C# Program to find the subarray with
// no pair sum divisible by K
using System;
using System.Collections;
class GFG {
// function to find the subarray with
// no pair sum divisible by k
static void subarrayDivisibleByK(int []arr,
int n, int k)
{
// hash table to store the remainders
// obtained on dividing by K
int []mp = new int[1000];
// s : starting index of the
// current subarray, e : ending
// index of the current subarray, maxs :
// starting index of the maximum
// size subarray so far, maxe : ending
// index of the maximum size subarray
// so far
int s = 0, e = 0, maxs = 0, maxe = 0;
// insert the first element in the set
mp[arr[0] % k]++;
for (int i = 1; i < n; i++)
{
int mod = arr[i] % k;
// Removing starting elements of current
// subarray while there is an element in
// set which makes a pair with mod[i] such
// that the pair sum is divisible.
while (mp[k - mod] != 0 ||
(mod == 0 && mp[mod] != 0))
{
mp[arr[s] % k]--;
s++;
}
// include the current element in
// the current subarray the ending
// index of the current subarray
// increments by one
mp[mod]++;
e++;
// compare the size of the current
// subarray with the maximum size so
// far
if ((e - s) > (maxe - maxs))
{
maxe = e;
maxs = s;
}
}
Console.Write("The maximum size is " +
(maxe - maxs + 1) +
" and the subarray is as follows\n");
for (int i = maxs; i <= maxe; i++)
Console.Write(arr[i] + " ");
}
// Driver Code
public static void Main()
{
int k = 3;
int []arr = {5, 10, 15, 20, 25};
int n = arr.Length;
subarrayDivisibleByK(arr, n, k);
}
}
// This code is contributed by
// Manish Shaw (manishshaw1)
PHP
<?php
// PHP Program to find the
// subarray with no pair
// sum divisible by K
// function to find the subarray
// with no pair sum divisible by k
function subarrayDivisibleByK($arr, $n, $k)
{
// hash table to store the remainders
// obtained on dividing by K
$mp = array_fill(0, 1000, 0);
// s : starting index of the
// current subarray, e : ending
// index of the current subarray, maxs :
// starting index of the maximum
// size subarray so far, maxe : ending
// index of the maximum size subarray
// so far
$s = 0;
$e = 0;
$maxs = 0;
$maxe = 0;
// insert the first
// element in the set
$mp[$arr[0] % $k]++;
for ($i = 1; $i < $n; $i++)
{
$mod = $arr[$i] % $k;
// Removing starting elements
// of current subarray while
// there is an element in set
// which makes a pair with
// mod[i] such that the pair
// sum is divisible.
while ($mp[$k - $mod] != 0 ||
($mod == 0 &&
$mp[$mod] != 0))
{
$mp[$arr[$s] % $k]--;
$s++;
}
// include the current element in
// the current subarray the ending
// index of the current subarray
// increments by one
$mp[$mod]++;
$e++;
// compare the size of the current
// subarray with the maximum size so
// far
if (($e - $s) > ($maxe - $maxs))
{
$maxe = $e;
$maxs = $s;
}
}
echo ("The maximum size is ".
($maxe - $maxs + 1).
" and the subarray is".
" as follows\n");
for ($i = $maxs; $i <= $maxe; $i++)
echo ($arr[$i]." ");
}
// Driver Code
$k = 3;
$arr = array(5, 10, 15, 20, 25);
$n = count($arr);
subarrayDivisibleByK($arr, $n, $k);
// This code is contributed by
// Manish Shaw (manishshaw1)
?>
JavaScript
<script>
// JavaScript Program to find the subarray with
// no pair sum divisible by K
// function to find the subarray with
// no pair sum divisible by k
function subarrayDivisibleByK(arr, n, k) {
// hash table to store the remainders
// obtained on dividing by K
var mp = new Array(1000).fill(0);
// s : starting index of the
// current subarray, e : ending
// index of the current subarray, maxs :
// starting index of the maximum
// size subarray so far, maxe : ending
// index of the maximum size subarray
// so far
var s = 0,
e = 0,
maxs = 0,
maxe = 0;
// insert the first element in the set
mp[arr[0] % k]++;
for (var i = 1; i < n; i++) {
var mod = arr[i] % k;
// Removing starting elements of current
// subarray while there is an element in
// set which makes a pair with mod[i] such
// that the pair sum is divisible.
while (mp[k - mod] != 0 || (mod == 0 && mp[mod] != 0)) {
mp[arr[s] % k]--;
s++;
}
// include the current element in
// the current subarray the ending
// index of the current subarray
// increments by one
mp[mod]++;
e++;
// compare the size of the current
// subarray with the maximum size so
// far
if (e - s > maxe - maxs) {
maxe = e;
maxs = s;
}
}
document.write(
"The maximum size is " +
(maxe - maxs + 1) +
" and the subarray is as follows<br>"
);
for (var i = maxs; i <= maxe; i++) document.write(arr[i] + " ");
}
// Driver Code
var k = 3;
var arr = [5, 10, 15, 20, 25];
var n = arr.length;
subarrayDivisibleByK(arr, n, k);
// This code is contributed by rdtank.
</script>
OutputThe maximum size is 2 and the subarray is as follows
10 15
Time Complexity : O(nlogn)
Auxiliary Space: O(n)
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