Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Length of longest subarray for each index in Array where element at that index is largest
Next article icon

Length of longest subarray whose sum is not divisible by integer K

Last Updated : 11 Jul, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] of size N and an integer k, our task is to find the length of longest subarray whose sum of elements is not divisible by k. If no such subarray exists then return -1.
Examples: 
 

Input: arr[] = {8, 4, 3, 1, 5, 9, 2}, k = 2 
Output: 5 
Explanation: 
The subarray is {8, 4, 3, 1, 5} with sum = 21, is not divisible by 2.
Input: arr[] = {6, 3, 12, 15}, k = 3 
Output: -1 
Explanation: 
There is no subarray which is not divisible by 3. 
 

 

Naive Approach: The idea is to consider all the subarrays and return the length of the longest subarray such that the sum of its elements is not divisible by k.
Time Complexity: O(N2) 
Auxiliary Space: O(N)
Efficient Approach: The main observation is that removing an element that is divisible by k will not contribute to the solution, but if we remove an element that is not divisible by k then the sum would not be divisible by k. 
 

  • Therefore, let the leftmost non-multiple of k be at index left, and the rightmost non-multiple of k be at index right.
  • Remove either the prefix elements up to index left, or the suffix element up to index right and remove the elements which have lesser number of elements.
  • There are two corner cases in this problem. First is, if every element of the array are divisible by k, then no such subarray exist so return -1. Secondly, if sum of the whole array is not divisible by k, then the subarray will be the array itself, so return the size of the array.

Below is the implementation of the above approach:
 

C++




// C++ Program to find the length of
// the longest subarray whose sum is
// not divisible by integer K
  
#include <bits/stdc++.h>
using namespace std;
  
// Function to find the longest subarray
// with sum is not divisible by k
int MaxSubarrayLength(int arr[], int n, int k)
{
    // left is the index of the
    // leftmost element that is
    // not divisible by k
    int left = -1;
  
    // right is the index of the
    // rightmost element that is
    // not divisible by k
    int right;
  
    // sum of the array
    int sum = 0;
  
    for (int i = 0; i < n; i++) {
  
        // Find the element that
        // is not multiple of k
        if ((arr[i] % k) != 0) {
  
            // left = -1 means we are
            // finding the leftmost
            // element that is not
            // divisible by k
            if (left == -1) {
                left = i;
            }
  
            // Updating the
            // rightmost element
            right = i;
        }
  
        // update the sum of the
        // array up to the index i
        sum += arr[i];
    }
  
    // Check if the sum of the
    // array is not divisible
    // by k, then return the
    // size of array
    if ((sum % k) != 0) {
        return n;
    }
  
    // All elements of array
    // are divisible by k,
    // then no such subarray
    // possible so return -1
    else if (left == -1) {
        return -1;
    }
  
    else {
        // length of prefix elements
        // that can be removed
        int prefix_length = left + 1;
  
        // length of suffix elements
        // that can be removed
        int suffix_length = n - right;
  
        // Return the length of
        // subarray after removing
        // the elements which have
        // lesser number of elements
        return n - min(prefix_length,
                       suffix_length);
    }
}
  
// Driver Code
int main()
{
  
    int arr[] = { 6, 3, 12, 15 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int K = 3;
  
    cout << MaxSubarrayLength(arr, n, K);
  
    return 0;
}
 
 

Java




// Java program to find the length of
// the longest subarray whose sum is
// not divisible by integer K
import java.util.*;
  
class GFG{
  
// Function to find the longest subarray
// with sum is not divisible by k
static int MaxSubarrayLength(int arr[], int n,
                                        int k)
{
      
    // left is the index of the
    // leftmost element that is
    // not divisible by k
    int left = -1;
  
    // right is the index of the
    // rightmost element that is
    // not divisible by k
    int right = 0;
  
    // sum of the array
    int sum = 0;
  
    for(int i = 0; i < n; i++)
    {
          
        // Find the element that
        // is not multiple of k
        if ((arr[i] % k) != 0) 
        {
  
            // left = -1 means we are
            // finding the leftmost
            // element that is not
            // divisible by k
            if (left == -1) 
            {
                left = i;
            }
  
            // Updating the
            // rightmost element
            right = i;
        }
  
        // Update the sum of the
        // array up to the index i
        sum += arr[i];
    }
  
    // Check if the sum of the
    // array is not divisible
    // by k, then return the
    // size of array
    if ((sum % k) != 0)
    {
        return n;
    }
  
    // All elements of array
    // are divisible by k,
    // then no such subarray
    // possible so return -1
    else if (left == -1)
    {
        return -1;
    }
    else 
    {
          
        // Length of prefix elements
        // that can be removed
        int prefix_length = left + 1;
  
        // Length of suffix elements
        // that can be removed
        int suffix_length = n - right;
  
        // Return the length of
        // subarray after removing
        // the elements which have
        // lesser number of elements
        return n - Math.min(prefix_length,
                            suffix_length);
    }
}
  
// Driver code
public static void main(String[] args)
{
    int arr[] = { 6, 3, 12, 15 };
    int n = arr.length;
    int K = 3;
      
    System.out.println(MaxSubarrayLength(arr, n, K));
}
}
  
// This code is contributed by offbeat
 
 

Python3




# Python3 program to find the length of
# the longest subarray whose sum is
# not divisible by integer 
  
# Function to find the longest subarray
# with sum is not divisible by k
def MaxSubarrayLength(arr, n, k):
  
    # left is the index of the
    # leftmost element that is
    # not divisible by k
    left = -1
  
    # sum of the array
    sum = 0
  
    for i in range(n):
  
        # Find the element that
        # is not multiple of k
        if ((arr[i] % k) != 0):
  
            # left = -1 means we are
            # finding the leftmost
            # element that is not
            # divisible by k
            if (left == -1):
                left = i
  
            # Updating the
            # rightmost element
            right = i
  
        # Update the sum of the
        # array up to the index i
        sum += arr[i]
  
    # Check if the sum of the
    # array is not divisible
    # by k, then return the
    # size of array
    if ((sum % k) != 0):
        return n
  
    # All elements of array
    # are divisible by k,
    # then no such subarray
    # possible so return -1
    elif(left == -1):
        return -1
  
    else:
          
        # length of prefix elements
        # that can be removed
        prefix_length = left + 1
  
        # length of suffix elements
        # that can be removed
        suffix_length = n - right
  
        # Return the length of
        # subarray after removing
        # the elements which have
        # lesser number of elements
        return n - min(prefix_length,
                       suffix_length)
                         
# Driver Code
if __name__ == "__main__":
  
    arr = [ 6, 3, 12, 15 ]
    n = len(arr)
    K = 3
  
    print(MaxSubarrayLength(arr, n, K))
  
# This code is contributed by chitranayal
 
 

C#




// C# program to find the length of
// the longest subarray whose sum is
// not divisible by integer K
using System;
  
class GFG{
  
// Function to find the longest subarray
// with sum is not divisible by k
static int MaxSubarrayLength(int []arr, int n,
                                        int k)
{
      
    // left is the index of the
    // leftmost element that is
    // not divisible by k
    int left = -1;
  
    // right is the index of the
    // rightmost element that is
    // not divisible by k
    int right = 0;
  
    // sum of the array
    int sum = 0;
  
    for(int i = 0; i < n; i++)
    {
          
        // Find the element that
        // is not multiple of k
        if ((arr[i] % k) != 0) 
        {
  
            // left = -1 means we are
            // finding the leftmost
            // element that is not
            // divisible by k
            if (left == -1) 
            {
                left = i;
            }
  
            // Updating the
            // rightmost element
            right = i;
        }
  
        // Update the sum of the
        // array up to the index i
        sum += arr[i];
    }
  
    // Check if the sum of the
    // array is not divisible
    // by k, then return the
    // size of array
    if ((sum % k) != 0)
    {
        return n;
    }
  
    // All elements of array
    // are divisible by k,
    // then no such subarray
    // possible so return -1
    else if (left == -1)
    {
        return -1;
    }
    else
    {
          
        // Length of prefix elements
        // that can be removed
        int prefix_length = left + 1;
  
        // Length of suffix elements
        // that can be removed
        int suffix_length = n - right;
  
        // Return the length of
        // subarray after removing
        // the elements which have
        // lesser number of elements
        return n - Math.Min(prefix_length,
                            suffix_length);
    }
}
  
// Driver code
public static void Main(string[] args)
{
    int []arr = { 6, 3, 12, 15 };
    int n = arr.Length;
    int K = 3;
      
    Console.Write(MaxSubarrayLength(arr, n, K));
}
}
  
// This code is contributed by rutvik_56
 
 

Javascript




<script>
  
// Javascript program to find the length of
// the longest subarray whose sum is
// not divisible by integer K
   
// Function to find the longest subarray
// with sum is not divisible by k
function MaxSubarrayLength(arr, n, k)
{
      
    // left is the index of the
    // leftmost element that is
    // not divisible by k
    let left = -1;
  
    // right is the index of the
    // rightmost element that is
    // not divisible by k
    let right = 0;
  
    // sum of the array
    let sum = 0;
  
    for(let i = 0; i < n; i++)
    {
          
        // Find the element that
        // is not multiple of k
        if ((arr[i] % k) != 0) 
        {
  
            // left = -1 means we are
            // finding the leftmost
            // element that is not
            // divisible by k
            if (left == -1) 
            {
                left = i;
            }
  
            // Updating the
            // rightmost element
            right = i;
        }
  
        // Update the sum of the
        // array up to the index i
        sum += arr[i];
    }
  
    // Check if the sum of the
    // array is not divisible
    // by k, then return the
    // size of array
    if ((sum % k) != 0)
    {
        return n;
    }
  
    // All elements of array
    // are divisible by k,
    // then no such subarray
    // possible so return -1
    else if (left == -1)
    {
        return -1;
    }
    else 
    {
          
        // Length of prefix elements
        // that can be removed
        let prefix_length = left + 1;
  
        // Length of suffix elements
        // that can be removed
        let suffix_length = n - right;
  
        // Return the length of
        // subarray after removing
        // the elements which have
        // lesser number of elements
        return n - Math.min(prefix_length,
                            suffix_length);
    }
}
  
// Driver Code
    let arr = [ 6, 3, 12, 15 ];
    let n = arr.length;
    let K = 3;
      
    document.write(MaxSubarrayLength(arr, n, K));
    
  // This code is contributed by target_2.
</script>
 
 
Output: 
-1

 

Time Complexity: O(N) 
Auxiliary Space: O(1)
 

Related Topic: Subarrays, Subsequences, and Subsets in Array



Next Article
Length of longest subarray for each index in Array where element at that index is largest
author
saltycode
Improve
Article Tags :
  • Arrays
  • C++ Programs
  • Competitive Programming
  • DSA
  • Mathematical
  • divisibility
  • prefix
  • subarray
  • Suffix
Practice Tags :
  • Arrays
  • Mathematical

Similar Reads

  • Length of longest subarray for each index in Array where element at that index is largest
    Given an array arr[] of size N, the task is to calculate, for i(0<=i<N), the maximum length of a subarray containing arr[i], where arr[i] is the maximum element. Example: Input : arr[ ] = {62, 97, 49, 59, 54, 92, 21}, N=7Output: 1 7 1 3 1 5 1Explanation: The maximum length of subarray in which
    15 min read
  • Longest unique subarray of an Array with maximum sum in another Array
    Given two arrays X[] and Y[] of size N, the task is to find the longest subarray in X[] containing only unique values such that a subarray with similar indices in Y[] should have a maximum sum. The value of array elements is in the range [0, 1000]. Examples: Input: N = 5, X[] = {0, 1, 2, 0, 2}, Y[]
    10 min read
  • Maximum length of subarray such that sum of the subarray is even
    Given an array of N elements. The task is to find the length of the longest subarray such that sum of the subarray is even.Examples: Input : N = 6, arr[] = {1, 2, 3, 2, 1, 4}Output : 5Explanation: In the example the subarray in range [2, 6] has sum 12 which is even, so the length is 5.Input : N = 4,
    11 min read
  • Find the longest subsequence of an array having LCM at most K
    Given an array arr[] of N elements and a positive integer K. The task is to find the longest sub-sequence in the array having LCM (Least Common Multiple) at most K. Print the LCM and the length of the sub-sequence, following the indexes (starting from 0) of the elements of the obtained sub-sequence.
    10 min read
  • Minimum MEX from all subarrays of length K
    Given an array arr[] consisting of N distinct positive integers and an integer K, the task is to find the minimum MEX from all subarrays of length K. The MEX is the smallest positive integer that is not present in the array. Examples: Input: arr[] = {1, 2, 3}, K = 2Output: 1Explanation:All subarrays
    7 min read
  • Longest subarray such that adjacent elements have at least one common digit | Set 1
    Given an array of N integers, write a program that prints the length of the longest subarray such that adjacent elements of the subarray have at least one digit in common. Examples: Input : 12 23 45 43 36 97 Output : 3 Explanation: The subarray is 45 43 36 which has 4 common in 45, 43 and 3 common i
    11 min read
  • C++ Program to Find the K-th Largest Sum Contiguous Subarray
    Given an array of integers. Write a program to find the K-th largest sum of contiguous subarray within the array of numbers which has negative and positive numbers. Examples:  Input: a[] = {20, -5, -1} k = 3 Output: 14 Explanation: All sum of contiguous subarrays are (20, 15, 14, -5, -6, -1) so the
    3 min read
  • Subsets with sum divisible by m
    Given an array of size n and an integer m, the task is to find the number of non-empty subsequences such that the sum of the subsequence is divisible by m. Note: The sum of all array elements in small, i.e., it is within integer range.m > 0.Examples: Input : arr[] = [1, 2, 3, 4], m = 2Output : 7
    15+ min read
  • Minimize the maximum element of N subarrays of size K
    Given an array arr[] and two integers N and K, the task is to choose non-overlapping N subarrays of size K such that the maximum element of all subarrays is minimum.Note: If it is not possible to choose N such subarrays then return -1. Examples: Input: arr[] = {1, 10, 3, 10, 2}, N = 3, K = 1 Output:
    8 min read
  • Maximum sum of pairs that are at least K distance apart in an array
    Given an array arr[] consisting of N integers and an integer K, the task is to find the maximum sum of pairs of elements that are separated by at least K indices. Examples: Input: arr[] = {2, 4, 1, 6, 8}, K = 2Output: 12Explanation:The elements {1, 4} are K(= 2) distance apart. The sum of pairs {4,
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences