Longest Subarray With Sum Divisible By K
Last Updated :
23 Jul, 2025
Given an arr[] containing n integers and a positive integer k, he problem is to find the longest subarray's length with the sum of the elements divisible by k.
Examples:
Input: arr[] = [2, 7, 6, 1, 4, 5], k = 3
Output: 4
Explanation: The subarray [7, 6, 1, 4] has sum = 18, which is divisible by 3.
Input: arr[] = [-2, 2, -5, 12, -11, -1, 7], k = 3
Output: 5
Explanation: The subarray [2, -5, 12, -11, -1], has sum = -3, which is divisible by 3.
Input: arr[] = [1, 2, -2], k = 5
Output: 2
Explanation: The subarray is [2, -2] with sum = 0, which is divisible by 5.
[Naive Approach] Using loop- Iterating over all subarrays
Consider all the subarray sums using two nested for loops and return the length of the longest subarray with a sum divisible by k. To avoid overflow while computing the sum of the subarray, we can keep track of (subarray sum % k) and if (subarray sum % k) results to 0, we can use its length to find the longest subarray divisible by k.
C++
// C++ Program to find the longest subarray with sum
// divisible by k by iterating over all subarrays
#include <iostream>
#include <vector>
using namespace std;
int longestSubarrayDivK(vector<int> &arr, int k) {
int res = 0;
for (int i = 0; i < arr.size(); i++) {
// Initialize sum for the current subarray
int sum = 0;
for (int j = i; j < arr.size(); j++) {
// Add the current element to the subarray sum
sum = (sum + arr[j]) % k;
// Update max length if sum is divisible by k
if (sum == 0)
res = max(res, j - i + 1);
}
}
return res;
}
int main() {
vector<int> arr = {2, 7, 6, 1, 4, 5};
int k = 3;
cout << longestSubarrayDivK(arr, k);
return 0;
}
C
// C Program to find the longest subarray with sum
// divisible by k by iterating over all subarrays
#include <stdio.h>
int longestSubarrayDivK(int arr[], int n, int k) {
int res = 0;
for (int i = 0; i < n; i++) {
// Initialize sum for the current subarray
int sum = 0;
for (int j = i; j < n; j++) {
// Add the current element to the subarray sum
sum = (sum + arr[j]) % k;
// Update max length if sum is divisible by k
if (sum == 0)
res = (res > (j - i + 1)) ? res : (j - i + 1);
}
}
return res;
}
int main() {
int arr[] = {2, 7, 6, 1, 4, 5};
int k = 3;
int n = sizeof(arr) / sizeof(arr[0]);
printf("%d\n", longestSubarrayDivK(arr, n, k));
return 0;
}
Java
// Java Program to find the longest subarray with sum
// divisible by k by iterating over all subarrays
import java.util.*;
class GfG {
static int longestSubarrayDivK(int[] arr, int k) {
int res = 0;
for (int i = 0; i < arr.length; i++) {
// Initialize sum for the current subarray
int sum = 0;
for (int j = i; j < arr.length; j++) {
// Add the current element to the subarray sum
sum = (sum + arr[j]) % k;
// Update max length if sum is divisible by k
if (sum == 0)
res = Math.max(res, j - i + 1);
}
}
return res;
}
public static void main(String[] args) {
int[] arr = {2, 7, 6, 1, 4, 5};
int k = 3;
System.out.println(longestSubarrayDivK(arr, k));
}
}
Python
# Python Program to find the longest subarray with sum
# divisible by k by iterating over all subarrays
def longestSubarrayDivK(arr, k):
res = 0
for i in range(len(arr)):
# Initialize sum for the current subarray
sum = 0
for j in range(i, len(arr)):
# Add the current element to the subarray sum
sum = (sum + arr[j]) % k;
# Update max length if sum is divisible by k
if sum == 0:
res = max(res, j - i + 1)
return res
if __name__ == "__main__":
arr = [2, 7, 6, 1, 4, 5]
k = 3
print(longestSubarrayDivK(arr, k))
C#
// C# Program to find the longest subarray with sum
// divisible by k by iterating over all subarrays
using System;
class GfG {
static int longestSubarrayDivK(int[] arr, int k) {
int res = 0;
for (int i = 0; i < arr.Length; i++) {
// Initialize sum for the current subarray
int sum = 0;
for (int j = i; j < arr.Length; j++) {
// Add the current element to the subarray sum
sum = (sum + arr[j]) % k;
// Update max length if sum is divisible by k
if (sum == 0)
res = Math.Max(res, j - i + 1);
}
}
return res;
}
static void Main(string[] args) {
int[] arr = {2, 7, 6, 1, 4, 5};
int k = 3;
Console.WriteLine(longestSubarrayDivK(arr, k));
}
}
JavaScript
// JavaScript Program to find the longest subarray with sum
// divisible by k by iterating over all subarrays
function longestSubarrayDivK(arr, k) {
let res = 0;
for (let i = 0; i < arr.length; i++) {
// Initialize sum for the current subarray
let sum = 0;
for (let j = i; j < arr.length; j++) {
// Add the current element to the subarray sum
sum = (sum + arr[j]) % k;
// Update max length if sum is divisible by k
if (sum === 0)
res = Math.max(res, j - i + 1);
}
}
return res;
}
// Driver Code
const arr = [2, 7, 6, 1, 4, 5];
const k = 3;
console.log(longestSubarrayDivK(arr, k));
Time Complexity: O(n^2)
Auxiliary Space: O(1)
[Expected Approach] Using Prefix Sum modulo k
The idea is to use Prefix Sum Technique along with Hashing. On observing carefully, we can say that if a subarray arr[i…j] has sum divisible by k, then (prefix sum[i] % k) will be equal to the (prefix sum[j] % k). So, we can iterate over arr[] while maintaining a hash map or dictionary to keep track of the first occurrence of of (prefix sum % k) at each index. For each index i, the longest subarray ending at i and having sum divisible by k will be equal to i - first occurrence of (prefix sum[i] % k).
Note: Negative value of (prefix sum mod k) needs to be handled separately in languages like C++, Java, C# and JavaScript, whereas in Python (prefix sum mod k) is always a non-negative value as it takes the sign of the divisor, that is k.
C++
// C++ Code to find longest Subarray With Sum Divisible
// By K using Prefix Sum and Hash map
#include <iostream>
#include <unordered_map>
#include <vector>
using namespace std;
int longestSubarrayDivK(vector<int> &arr, int k) {
int n = arr.size(), res = 0;
unordered_map<int, int> prefIdx;
int sum = 0;
// Iterate over all ending points
for (int i = 0; i < n; i++) {
// prefix sum mod k (handling negative prefix sum)
sum = ((sum + arr[i]) % k + k) % k;
// If sum == 0, then update result with the
// length of subarray arr[0...i]
if (sum == 0)
res = i + 1;
// Update max length for repeating sum
else if (prefIdx.find(sum) != prefIdx.end()) {
res = max(res, i - prefIdx[sum]);
}
// Store the first occurrence of sum
else {
prefIdx[sum] = i;
}
}
return res;
}
int main() {
vector<int> arr = {2, 7, 6, 1, 4, 5};
int k = 3;
cout << longestSubarrayDivK(arr, k);
}
Java
// Java Code to find longest Subarray With Sum Divisible
// By K using Prefix Sum and Hash map
import java.util.HashMap;
import java.util.Map;
class GfG {
static int longestSubarrayDivK(int[] arr, int k) {
int n = arr.length, res = 0;
Map<Integer, Integer> prefIdx = new HashMap<>();
int sum = 0;
// Iterate over all ending points
for (int i = 0; i < n; i++) {
// prefix sum mod k (handling negative prefix sum)
sum = ((sum + arr[i]) % k + k) % k;
// If sum == 0, then update result with the
// length of subarray arr[0...i]
if (sum == 0)
res = i + 1;
// Update max length for repeating sum
else if (prefIdx.containsKey(sum)) {
res = Math.max(res, i - prefIdx.get(sum));
}
// Store the first occurrence of sum
else {
prefIdx.put(sum, i);
}
}
return res;
}
public static void main(String[] args) {
int[] arr = {2, 7, 6, 1, 4, 5};
int k = 3;
System.out.println(longestSubarrayDivK(arr, k));
}
}
Python
# Python Code to find longest Subarray With Sum Divisible
# By K using Prefix Sum and Hash map
def longestSubarrayDivK(arr, k):
n = len(arr)
res = 0
prefIdx = {}
sum = 0
# Iterate over all ending points
for i in range(n):
# prefix sum mod k
sum = (sum + arr[i]) % k
# If sum == 0, then update result with the
# length of subarray arr[0...i]
if sum == 0:
res = i + 1
# Update max length for repeating sum
elif sum in prefIdx:
res = max(res, i - prefIdx[sum])
# Store the first occurrence of sum
else:
prefIdx[sum] = i
return res
if __name__ == "__main__":
arr = [2, 7, 6, 1, 4, 5]
k = 3
print(longestSubarrayDivK(arr, k))
C#
// C# Code to find longest Subarray With Sum Divisible
// By K using Prefix Sum and Hash map
using System;
using System.Collections.Generic;
class GfG {
static int LongestSubarrayDivK(int[] arr, int k) {
int n = arr.Length, res = 0;
Dictionary<int, int> prefIdx = new Dictionary<int, int>();
int sum = 0;
// Iterate over all ending points
for (int i = 0; i < n; i++) {
// prefix sum mod k (handling negative prefix sum)
sum = ((sum + arr[i]) % k + k) % k;
// If sum == 0, then update result with the
// length of subarray arr[0...i]
if (sum == 0)
res = i + 1;
// Update max length for repeating sum
else if (prefIdx.ContainsKey(sum)) {
res = Math.Max(res, i - prefIdx[sum]);
}
// Store the first occurrence of sum
else {
prefIdx[sum] = i;
}
}
return res;
}
static void Main() {
int[] arr = {2, 7, 6, 1, 4, 5};
int k = 3;
Console.WriteLine(LongestSubarrayDivK(arr, k));
}
}
JavaScript
// JavaScript Code to find longest Subarray With Sum Divisible
// By K using Prefix Sum and Hash map
function longestSubarrayDivK(arr, k) {
let n = arr.length, res = 0;
let prefIdx = new Map();
let sum = 0;
// Iterate over all ending points
for (let i = 0; i < n; i++) {
// prefix sum mod k (handling negative prefix sum)
sum = ((sum + arr[i]) % k + k) % k;
// If sum == 0, then update result with the
// length of subarray arr[0...i]
if (sum === 0)
res = i + 1;
// Update max length for repeating sum
else if (prefIdx.has(sum)) {
res = Math.max(res, i - prefIdx.get(sum));
}
// Store the first occurrence of sum
else {
prefIdx.set(sum, i);
}
}
return res;
}
// Driver Code
let arr = [2, 7, 6, 1, 4, 5];
let k = 3;
console.log(longestSubarrayDivK(arr, k));
Time Complexity: O(n), as we are iterating over the array only once.
Auxiliary Space: O(min(n, k)), as at most k keys can be present in the hash map or dictionary.
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