Longest subarray with sum not divisible by X
Last Updated :
23 Mar, 2023
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++
#include <bits/stdc++.h>
using namespace std;
void max_length( int n, int x,vector< int > a)
{
int maxm = -1, start = -1, end = -1;
for ( int i = 0; i < n; i++) {
for ( int j = i; j < n; j++) {
int sum = 0;
for ( int k = i; k <= j; k++) {
sum += a[k];
}
if (sum % x != 0 && j - i + 1 > maxm) {
maxm = j - i + 1;
start = i;
end = j;
}
}
}
if (maxm == -1) {
cout << "-1\n" ;
}
else {
for ( int i = start; i <= end; i++) {
cout << a[i] << " " ;
}
cout << "\n" ;
}
}
int main()
{
int x = 3;
vector< int > v = { 1, 3, 2, 6 };
int N = v.size();
max_length(N, x, v);
return 0;
}
|
Java
import java.util.*;
class Main {
static void max_length( int n, int x,
ArrayList<Integer> a)
{
int maxm = - 1 , start = - 1 , end = - 1 ;
for ( int i = 0 ; i < n; i++) {
for ( int j = i; j < n; j++) {
int sum = 0 ;
for ( int k = i; k <= j; k++) {
sum += a.get(k);
}
if (sum % x != 0 && j - i + 1 > maxm) {
maxm = j - i + 1 ;
start = i;
end = j;
}
}
}
if (maxm == - 1 ) {
System.out.println( "-1" );
}
else {
for ( int i = start; i <= end; i++) {
System.out.print(a.get(i) + " " );
}
System.out.println();
}
}
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
def max_length(n, x, a):
maxm = - 1
start = - 1
end = - 1
for i in range ( 0 , n):
for j in range (i, n):
sum1 = 0
for k in range (i, j + 1 ):
sum1 + = a[k]
if sum1 % x ! = 0 and j - i + 1 > maxm:
maxm = j - i + 1
start = i
end = j
if maxm = = - 1 :
print ( "-1" )
else :
for i in range (start, end + 1 ):
print (a[i], end = " " )
print ()
if __name__ = = "__main__" :
x = 3
v = [ 1 , 3 , 2 , 6 ]
N = len (v)
max_length(N, x, v)
|
C#
using System;
using System.Collections.Generic;
using System.Linq;
class GFG {
static void max_length( int n, int x, List< int > a)
{
int maxm = -1, start = -1, end = -1;
for ( int i = 0; i < n; i++) {
for ( int j = i; j < n; j++) {
int sum = 0;
for ( int k = i; k <= j; k++) {
sum += a[k];
}
if (sum % x != 0 && j - i + 1 > maxm) {
maxm = j - i + 1;
start = i;
end = j;
}
}
}
if (maxm == -1) {
Console.WriteLine( "-1" );
}
else {
for ( int i = start; i <= end; i++) {
Console.Write(a[i] + " " );
}
Console.WriteLine();
}
}
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
function max_length(n, x, a) {
let maxm = -1;
let start = -1;
let end = -1;
for (let i = 0; i < n; i++) {
for (let j = i; j < n; j++) {
let sum1 = 0;
for (let k = i; k <= j; k++) {
sum1 += a[k];
}
if (sum1 % x !== 0 && j - i + 1 > maxm) {
maxm = j - i + 1;
start = i;
end = j;
}
}
}
if (maxm === -1) {
console.log( "-1" );
}
else { temp= ""
for (let i = start; i <= end; i++) {
temp = temp + a[i]+ " " ;
}
console.log(temp);
}
}
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>
#include <bits/stdc++.h>
using namespace std;
void max_length( int N, int x,
vector< int >& v)
{
int i, a;
vector< int > preff, suff;
int ct = 0;
for (i = 0; i < N; i++) {
a = v[i];
if (a % x == 0) {
ct += 1;
}
}
if (ct == N) {
cout << -1 << endl;
return ;
}
reverse(v.begin(), v.end());
suff.push_back(v[0]);
for (i = 1; i < N; i++) {
suff.push_back(v[i]
+ suff[i - 1]);
}
reverse(v.begin(), v.end());
reverse(suff.begin(), suff.end());
preff.push_back(v[0]);
for (i = 1; i < N; i++) {
preff.push_back(v[i]
+ preff[i - 1]);
}
int ans = 0;
int lp = 0;
int rp = N - 1;
for (i = 0; i < N; i++) {
if (suff[i] % x != 0
&& (ans < (N - 1))) {
lp = i;
rp = N - 1;
ans = max(ans, N - i);
}
if (preff[i] % x != 0
&& (ans < (i + 1))) {
lp = 0;
rp = i;
ans = max(ans, i + 1);
}
}
for (i = lp; i <= rp; i++) {
cout << v[i] << " " ;
}
}
int main()
{
int x = 3;
vector< int > v = { 1, 3, 2, 6 };
int N = v.size();
max_length(N, x, v);
return 0;
}
|
Java
import java.util.*;
class GFG{
static void max_length( int N, int x,
int []v)
{
int i, a;
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 (a % x == 0 )
{
ct += 1 ;
}
}
if (ct == N)
{
System.out.print(- 1 + "\n" );
return ;
}
v = reverse(v);
suff.add(v[ 0 ]);
for (i = 1 ; i < N; i++)
{
suff.add(v[i] + suff.get(i - 1 ));
}
v = reverse(v);
Collections.reverse(suff);
preff.add(v[ 0 ]);
for (i = 1 ; i < N; i++)
{
preff.add(v[i] + preff.get(i - 1 ));
}
int ans = 0 ;
int lp = 0 ;
int rp = N - 1 ;
for (i = 0 ; i < N; i++)
{
if (suff.get(i) % x != 0 &&
(ans < (N - 1 )))
{
lp = i;
rp = N - 1 ;
ans = Math.max(ans, N - i);
}
if (preff.get(i) % x != 0 &&
(ans < (i + 1 )))
{
lp = 0 ;
rp = i;
ans = Math.max(ans, i + 1 );
}
}
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;
}
public static void main(String[] args)
{
int x = 3 ;
int []v = { 1 , 3 , 2 , 6 };
int N = v.length;
max_length(N, x, v);
}
}
|
Python3
def max_length(N, x, v):
preff, suff = [], []
ct = 0
for i in range (N):
a = v[i]
if a % x = = 0 :
ct + = 1
if ct = = N:
print ( - 1 )
return
v.reverse()
suff.append(v[ 0 ])
for i in range ( 1 , N):
suff.append(v[i] + suff[i - 1 ])
v.reverse()
suff.reverse()
preff.append(v[ 0 ])
for i in range ( 1 , N):
preff.append(v[i] + preff[i - 1 ])
ans = 0
lp = 0
rp = N - 1
for i in range (N):
if suff[i] % x ! = 0 and ans < N - 1 :
lp = i
rp = N - 1
ans = max (ans, N - i)
if preff[i] % x ! = 0 and ans < i + 1 :
lp = 0
rp = i
ans = max (ans, i + 1 )
for i in range (lp, rp + 1 ):
print (v[i], end = " " )
x = 3
v = [ 1 , 3 , 2 , 6 ]
N = len (v)
max_length(N, x, v)
|
C#
using System;
using System.Collections.Generic;
class GFG{
static void max_length( int N, int x,
int []v)
{
int i, a;
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 (a % x == 0)
{
ct += 1;
}
}
if (ct == N)
{
Console.Write(-1 + "\n" );
return ;
}
v = reverse(v);
suff.Add(v[0]);
for (i = 1; i < N; i++)
{
suff.Add(v[i] + suff[i - 1]);
}
v = reverse(v);
suff.Reverse();
preff.Add(v[0]);
for (i = 1; i < N; i++)
{
preff.Add(v[i] + preff[i - 1]);
}
int ans = 0;
int lp = 0;
int rp = N - 1;
for (i = 0; i < N; i++)
{
if (suff[i] % x != 0 &&
(ans < (N - 1)))
{
lp = i;
rp = N - 1;
ans = Math.Max(ans, N - i);
}
if (preff[i] % x != 0 &&
(ans < (i + 1)))
{
lp = 0;
rp = i;
ans = Math.Max(ans, i + 1);
}
}
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;
}
public static void Main(String[] args)
{
int x = 3;
int []v = { 1, 3, 2, 6 };
int N = v.Length;
max_length(N, x, v);
}
}
|
Javascript
function max_length( N, x,
v)
{
let i, a;
let preff = [], suff = [];
let ct = 0;
for (i = 0; i < N; i++) {
a = v[i];
if (a % x == 0) {
ct += 1;
}
}
if (ct == N) {
console.log(-1)
return ;
}
v.reverse()
suff.push(v[0]);
for (i = 1; i < N; i++) {
suff.push(v[i]
+ suff[i - 1]);
}
v.reverse()
suff.reverse()
preff.push(v[0]);
for (i = 1; i < N; i++) {
preff.push(v[i]
+ preff[i - 1]);
}
let ans = 0;
let lp = 0;
let rp = N - 1;
for (i = 0; i < N; i++) {
if (suff[i] % x != 0
&& (ans < (N - 1))) {
lp = i;
rp = N - 1;
ans = Math.max(ans, N - i);
}
if (preff[i] % x != 0
&& (ans < (i + 1))) {
lp = 0;
rp = i;
ans = Math.max(ans, i + 1);
}
}
for (i = lp; i <= rp; i++) {
process.stdout.write(v[i] + " " );
}
}
let x = 3;
let v = [ 1, 3, 2, 6 ];
let N = v.length;
max_length(N, x, v);
|
Time Complexity: O(N)
Auxiliary Space: O(N)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...