Longest subarray with sum not divisible by X
Last Updated :
15 Jul, 2025
Given an array arr[] and an integer X, the task is to print the longest subarray such that the sum of its elements isn't divisible by X. If no such subarray exists, print "-1".
Note: If more than one subarray exists with the given property, print any one of them.
Examples:
Input: arr[] = {1, 2, 3} X = 3
Output: 2 3
Explanation:
The subarray {2, 3} has a sum of elements 5, which isn't divisible by 3.
Input: arr[] = {2, 6} X = 2
Output: -1
Explanation:
All possible subarrays {1}, {2}, {1, 2} have an even sum.
Therefore, the answer is -1.
Naive Approach: The simplest approach to solve the problem is to generate all possible subarrays and keep calculating its sum. If any subarray is found to have sum not divisible by X, compare the length with maximum length obtained(maxm) and update the maxm accordingly and update the starting index and ending index of the subarray. Finally, print the subarray having the stored starting and ending indices. If there is no such subarray then print "-1".
C++
// C++ Program to implement
// the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to print the longest
// subarray with sum of elements
// not divisible by X
void max_length(int n, int x,vector<int> a)
{
// Variable to store start and end index
int maxm = -1, start = -1, end = -1;
// traversing to generate all subarray
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
// variable to store sum
int sum = 0;
for (int k = i; k <= j; k++) {
sum += a[k];
}
// Checking if sum is divisible by x
// or not. If not then update the length
// if it greater than all previous length
if (sum % x != 0 && j - i + 1 > maxm) {
maxm = j - i + 1;
start = i;
end = j;
}
}
}
// If there is no such subarray then print “-1”
if (maxm == -1) {
cout << "-1\n";
}
// print the subarray having the stored starting and ending indices
else {
for (int i = start; i <= end; i++) {
cout << a[i] << " ";
}
cout << "\n";
}
}
// Driver Code
int main()
{
int x = 3;
vector<int> v = { 1, 3, 2, 6 };
int N = v.size();
max_length(N, x, v);
return 0;
}
// This code is contributed by Pushpesh Raj.
Java
// Java Program to implement
// the above approach
import java.util.*;
class Main {
// Function to print the longest
// subarray with sum of elements
// not divisible by X
static void max_length(int n, int x,
ArrayList<Integer> a)
{
// Variable to store start and end index
int maxm = -1, start = -1, end = -1;
// traversing to generate all subarray
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
// variable to store sum
int sum = 0;
for (int k = i; k <= j; k++) {
sum += a.get(k);
}
// Checking if sum is divisible by x
// or not. If not then update the length
// if it greater than all previous length
if (sum % x != 0 && j - i + 1 > maxm) {
maxm = j - i + 1;
start = i;
end = j;
}
}
}
// If there is no such subarray then print “-1”
if (maxm == -1) {
System.out.println("-1");
}
// print the subarray having the stored starting and
// ending indices
else {
for (int i = start; i <= end; i++) {
System.out.print(a.get(i) + " ");
}
System.out.println();
}
}
// Driver Code
public static void main(String[] args)
{
int x = 3;
ArrayList<Integer> v = new ArrayList<Integer>(
Arrays.asList(1, 3, 2, 6));
int N = v.size();
max_length(N, x, v);
}
}
Python3
# Python Program to implement
# the above approach
def max_length(n, x, a):
# Variable to store start and end index
maxm = -1
start = -1
end = -1
# traversing to generate all subarray
for i in range(0, n):
for j in range(i, n):
# variable to store sum
sum1 = 0
for k in range(i, j + 1):
sum1 += a[k]
# Checking if sum is divisible by x
# or not. If not then update the length
# if it greater than all previous length
if sum1 % x != 0 and j - i + 1 > maxm:
maxm = j - i + 1
start = i
end = j
# If there is no such subarray then print “-1”
if maxm == -1:
print("-1")
# print the subarray having the stored starting and ending indices
else:
for i in range(start, end + 1):
print(a[i], end=" ")
print()
# Driver Code
if __name__ == "__main__":
x = 3
v = [1, 3, 2, 6]
N = len(v)
max_length(N, x, v)
C#
// C# Program to implement
// the above approach
using System;
using System.Collections.Generic;
using System.Linq;
class GFG {
// Function to print the longest
// subarray with sum of elements
// not divisible by X
static void max_length(int n, int x, List<int> a)
{
// Variable to store start and end index
int maxm = -1, start = -1, end = -1;
// traversing to generate all subarray
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
// variable to store sum
int sum = 0;
for (int k = i; k <= j; k++) {
sum += a[k];
}
// Checking if sum is divisible by x
// or not. If not then update the length
// if it greater than all previous length
if (sum % x != 0 && j - i + 1 > maxm) {
maxm = j - i + 1;
start = i;
end = j;
}
}
}
// If there is no such subarray then print “-1”
if (maxm == -1) {
Console.WriteLine("-1");
}
// print the subarray having the stored starting and
// ending indices
else {
for (int i = start; i <= end; i++) {
Console.Write(a[i] + " ");
}
Console.WriteLine();
}
}
// Driver Code
static void Main(string[] args)
{
int x = 3;
List<int> v = new List<int>{ 1, 3, 2, 6 };
int N = v.Count;
max_length(N, x, v);
}
}
JavaScript
// JavaScript program to implement
// the above approach
function max_length(n, x, a) {
// Variable to store start and end index
let maxm = -1;
let start = -1;
let end = -1;
// traversing to generate all subarray
for (let i = 0; i < n; i++) {
for (let j = i; j < n; j++) {
// variable to store sum
let sum1 = 0;
for (let k = i; k <= j; k++) {
sum1 += a[k];
}
// Checking if sum is divisible by x
// or not. If not then update the length
// if it greater than all previous length
if (sum1 % x !== 0 && j - i + 1 > maxm) {
maxm = j - i + 1;
start = i;
end = j;
}
}
}
// If there is no such subarray then print “-1”
if (maxm === -1) {
console.log("-1");
}
// print the subarray having the stored starting and ending indices
else { temp=""
for (let i = start; i <= end; i++) {
temp = temp + a[i]+" ";
}
console.log(temp);
}
}
// Driver Code
let x = 3;
let v = [1, 3, 2, 6];
let N = v.length;
max_length(N, x, v);
Time Complexity: O(N2)
Auxiliary Space: O(1)
Efficient Approach: To optimize the above approach we will find the prefix and suffix array sum. Follow the steps below:
- Generate the prefix sum array and suffix sum array.
- Iterate from [0, N - 1] using Two Pointers and choose the prefix and suffix sum of the element at each index which is not divisible by X. Store the starting index and ending index of the subarray.
- After completing the above steps, if there exist a subarray with sum not divisible by X, then print the subarray having the stored starting and ending indices.
- If there is no such subarray then print "-1".
Below is the implementation of the above approach:
C++
#include <iostream>
// C++ Program to implement
// the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to print the longest
// subarray with sum of elements
// not divisible by X
void max_length(int N, int x,
vector<int>& v)
{
int i, a;
// Pref[] stores the prefix sum
// Suff[] stores the suffix sum
vector<int> preff, suff;
int ct = 0;
for (i = 0; i < N; i++) {
a = v[i];
// If array element is
// divisibile by x
if (a % x == 0) {
// Increase count
ct += 1;
}
}
// If all the array elements
// are divisible by x
if (ct == N) {
// No subarray possible
cout << -1 << endl;
return;
}
// Reverse v to calculate the
// suffix sum
reverse(v.begin(), v.end());
suff.push_back(v[0]);
// Calculate the suffix sum
for (i = 1; i < N; i++) {
suff.push_back(v[i]
+ suff[i - 1]);
}
// Reverse to original form
reverse(v.begin(), v.end());
// Reverse the suffix sum array
reverse(suff.begin(), suff.end());
preff.push_back(v[0]);
// Calculate the prefix sum
for (i = 1; i < N; i++) {
preff.push_back(v[i]
+ preff[i - 1]);
}
int ans = 0;
// Stores the starting index
// of required subarray
int lp = 0;
// Stores the ending index
// of required subarray
int rp = N - 1;
for (i = 0; i < N; i++) {
// If suffix sum till i-th
// index is not divisible by x
if (suff[i] % x != 0
&& (ans < (N - 1))) {
lp = i;
rp = N - 1;
// Update the answer
ans = max(ans, N - i);
}
// If prefix sum till i-th
// index is not divisible by x
if (preff[i] % x != 0
&& (ans < (i + 1))) {
lp = 0;
rp = i;
// Update the answer
ans = max(ans, i + 1);
}
}
// Print the longest subarray
for (i = lp; i <= rp; i++) {
cout << v[i] << " ";
}
}
// Driver Code
int main()
{
int x = 3;
vector<int> v = { 1, 3, 2, 6 };
int N = v.size();
max_length(N, x, v);
return 0;
}
Java
// Java program to implement
// the above approach
import java.util.*;
class GFG{
// Function to print the longest
// subarray with sum of elements
// not divisible by X
static void max_length(int N, int x,
int []v)
{
int i, a;
// Pref[] stores the prefix sum
// Suff[] stores the suffix sum
List<Integer> preff = new Vector<Integer>();
List<Integer> suff = new Vector<Integer>();
int ct = 0;
for(i = 0; i < N; i++)
{
a = v[i];
// If array element is
// divisibile by x
if (a % x == 0)
{
// Increase count
ct += 1;
}
}
// If all the array elements
// are divisible by x
if (ct == N)
{
// No subarray possible
System.out.print(-1 + "\n");
return;
}
// Reverse v to calculate the
// suffix sum
v = reverse(v);
suff.add(v[0]);
// Calculate the suffix sum
for(i = 1; i < N; i++)
{
suff.add(v[i] + suff.get(i - 1));
}
// Reverse to original form
v = reverse(v);
// Reverse the suffix sum array
Collections.reverse(suff);
preff.add(v[0]);
// Calculate the prefix sum
for(i = 1; i < N; i++)
{
preff.add(v[i] + preff.get(i - 1));
}
int ans = 0;
// Stores the starting index
// of required subarray
int lp = 0;
// Stores the ending index
// of required subarray
int rp = N - 1;
for(i = 0; i < N; i++)
{
// If suffix sum till i-th
// index is not divisible by x
if (suff.get(i) % x != 0 &&
(ans < (N - 1)))
{
lp = i;
rp = N - 1;
// Update the answer
ans = Math.max(ans, N - i);
}
// If prefix sum till i-th
// index is not divisible by x
if (preff.get(i) % x != 0 &&
(ans < (i + 1)))
{
lp = 0;
rp = i;
// Update the answer
ans = Math.max(ans, i + 1);
}
}
// Print the longest subarray
for(i = lp; i <= rp; i++)
{
System.out.print(v[i] + " ");
}
}
static int[] reverse(int a[])
{
int i, n = a.length, t;
for(i = 0; i < n / 2; i++)
{
t = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = t;
}
return a;
}
// Driver Code
public static void main(String[] args)
{
int x = 3;
int []v = { 1, 3, 2, 6 };
int N = v.length;
max_length(N, x, v);
}
}
// This code is contributed by PrinciRaj1992
Python3
# Python3 program to implement
# the above approach
# Function to print the longest
# subarray with sum of elements
# not divisible by X
def max_length(N, x, v):
# Pref[] stores the prefix sum
# Suff[] stores the suffix sum
preff, suff = [], []
ct = 0
for i in range(N):
a = v[i]
# If array element is
# divisibile by x
if a % x == 0:
# Increase count
ct += 1
# If all the array elements
# are divisible by x
if ct == N:
# No subarray possible
print(-1)
return
# Reverse v to calculate the
# suffix sum
v.reverse()
suff.append(v[0])
# Calculate the suffix sum
for i in range(1, N):
suff.append(v[i] + suff[i - 1])
# Reverse to original form
v.reverse()
# Reverse the suffix sum array
suff.reverse()
preff.append(v[0])
# Calculate the prefix sum
for i in range(1, N):
preff.append(v[i] + preff[i - 1])
ans = 0
# Stores the starting index
# of required subarray
lp = 0
# Stores the ending index
# of required subarray
rp = N - 1
for i in range(N):
# If suffix sum till i-th
# index is not divisible by x
if suff[i] % x != 0 and ans < N - 1:
lp = i
rp = N - 1
# Update the answer
ans = max(ans, N - i)
# If prefix sum till i-th
# index is not divisible by x
if preff[i] % x != 0 and ans < i + 1:
lp = 0
rp = i
# Update the answer
ans = max(ans, i + 1)
# Print the longest subarray
for i in range(lp, rp + 1):
print(v[i], end = " ")
# Driver code
x = 3
v = [ 1, 3, 2, 6 ]
N = len(v)
max_length(N, x, v)
# This code is contributed by Stuti Pathak
C#
// C# program to implement
// the above approach
using System;
using System.Collections.Generic;
class GFG{
// Function to print the longest
// subarray with sum of elements
// not divisible by X
static void max_length(int N, int x,
int []v)
{
int i, a;
// Pref[] stores the prefix sum
// Suff[] stores the suffix sum
List<int> preff = new List<int>();
List<int> suff = new List<int>();
int ct = 0;
for(i = 0; i < N; i++)
{
a = v[i];
// If array element is
// divisibile by x
if (a % x == 0)
{
// Increase count
ct += 1;
}
}
// If all the array elements
// are divisible by x
if (ct == N)
{
// No subarray possible
Console.Write(-1 + "\n");
return;
}
// Reverse v to calculate the
// suffix sum
v = reverse(v);
suff.Add(v[0]);
// Calculate the suffix sum
for(i = 1; i < N; i++)
{
suff.Add(v[i] + suff[i - 1]);
}
// Reverse to original form
v = reverse(v);
// Reverse the suffix sum array
suff.Reverse();
preff.Add(v[0]);
// Calculate the prefix sum
for(i = 1; i < N; i++)
{
preff.Add(v[i] + preff[i - 1]);
}
int ans = 0;
// Stores the starting index
// of required subarray
int lp = 0;
// Stores the ending index
// of required subarray
int rp = N - 1;
for(i = 0; i < N; i++)
{
// If suffix sum till i-th
// index is not divisible by x
if (suff[i] % x != 0 &&
(ans < (N - 1)))
{
lp = i;
rp = N - 1;
// Update the answer
ans = Math.Max(ans, N - i);
}
// If prefix sum till i-th
// index is not divisible by x
if (preff[i] % x != 0 &&
(ans < (i + 1)))
{
lp = 0;
rp = i;
// Update the answer
ans = Math.Max(ans, i + 1);
}
}
// Print the longest subarray
for(i = lp; i <= rp; i++)
{
Console.Write(v[i] + " ");
}
}
static int[] reverse(int []a)
{
int i, n = a.Length, t;
for(i = 0; i < n / 2; i++)
{
t = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = t;
}
return a;
}
// Driver Code
public static void Main(String[] args)
{
int x = 3;
int []v = { 1, 3, 2, 6 };
int N = v.Length;
max_length(N, x, v);
}
}
// This code is contributed by PrinciRaj1992
JavaScript
// JS Program to implement
// the above approach
// Function to print the longest
// subarray with sum of elements
// not divisible by X
function max_length( N, x,
v)
{
let i, a;
// Pref[] stores the prefix sum
// Suff[] stores the suffix sum
let preff = [], suff = [];
let ct = 0;
for (i = 0; i < N; i++) {
a = v[i];
// If array element is
// divisibile by x
if (a % x == 0) {
// Increase count
ct += 1;
}
}
// If all the array elements
// are divisible by x
if (ct == N) {
// No subarray possible
console.log(-1)
return;
}
// Reverse v to calculate the
// suffix sum
v.reverse()
suff.push(v[0]);
// Calculate the suffix sum
for (i = 1; i < N; i++) {
suff.push(v[i]
+ suff[i - 1]);
}
// Reverse to original form
v.reverse()
// Reverse the suffix sum array
suff.reverse()
preff.push(v[0]);
// Calculate the prefix sum
for (i = 1; i < N; i++) {
preff.push(v[i]
+ preff[i - 1]);
}
let ans = 0;
// Stores the starting index
// of required subarray
let lp = 0;
// Stores the ending index
// of required subarray
let rp = N - 1;
for (i = 0; i < N; i++) {
// If suffix sum till i-th
// index is not divisible by x
if (suff[i] % x != 0
&& (ans < (N - 1))) {
lp = i;
rp = N - 1;
// Update the answer
ans = Math.max(ans, N - i);
}
// If prefix sum till i-th
// index is not divisible by x
if (preff[i] % x != 0
&& (ans < (i + 1))) {
lp = 0;
rp = i;
// Update the answer
ans = Math.max(ans, i + 1);
}
}
// Print the longest subarray
for (i = lp; i <= rp; i++) {
process.stdout.write(v[i] + " ");
}
}
// Driver Code
let x = 3;
let v = [ 1, 3, 2, 6 ];
let N = v.length;
max_length(N, x, v);
// This code is contributed by phasing17
Time Complexity: O(N)
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