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:
Longest Subarray With Sum Divisible By K
Next article icon

Count of longest possible subarrays with sum not divisible by K

Last Updated : 12 May, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array of integers arr[] and a positive integer K, the task is to find the count of the longest possible subarrays with sum of its elements not divisible by K.

Examples: 

Input: arr[] = {2, 3, 4, 6}, K = 3 
Output: 1 
Explanation: There is only one longest possible subarray of size 3 i.e. {3, 4, 6} having a sum 13, which is not divisible by K = 3. 

Input: arr[] = {2, 4, 3, 5, 1}, K = 3 
Output: 2 
Explanation: There are 2 longest possible subarrays of size 4 i.e. {2, 4, 3, 5} and {4, 3, 5, 1} having a sum 14 and 13 respectively, which is not divisible by K = 3. 
 

Approach:  

  1. Check if the sum of all the elements of the array is divisible by K
  2. If the sum is not divisible by K, return 1 as the longest subarray would be of size N.
  3. Else 
    • Find the index of the first number not divisible by K. Let that be L.
    • Find the index of the last number not divisible by K. Let that be R.
    • Remove the elements all the way up to index L and find the size of the subarray. Remove the elements beyond R and find the size of this subarray as well. Whichever length is greater, that will be the size of the longest subarray not divisible by K.
    • Using this length as the window size, apply the sliding window technique on the arr[] to find out the count of sub-arrays of the size obtained above which are not divisible by K.

Below is the implementation of the above approach:  

C++




// C++ program for the above problem
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the count of
// longest subarrays with sum not
// divisible by K
int CountLongestSubarrays(
    int arr[], int n, int k)
{
 
    // Sum of all elements in
    // an array
    int i, s = 0;
    for (i = 0; i < n; ++i) {
        s += arr[i];
    }
 
    // If overall sum is not
    // divisible then return
    // 1, as only one subarray
    // of size n is possible
    if (s % k) {
        return 1;
    }
    else {
        int ini = 0;
 
        // Index of the first number
        // not divisible by K
        while (ini < n
               && arr[ini] % k == 0) {
            ++ini;
        }
 
        int final = n - 1;
 
        // Index of the last number
        // not divisible by K
        while (final >= 0
               && arr[final] % k == 0) {
            --final;
        }
 
        int len, sum = 0, count = 0;
        // Subarray doesn't exist
        if (ini == n) {
            return -1;
        }
        else {
            len = max(n - 1 - ini,
                      final);
        }
 
        // Sum of the window
        for (i = 0; i < len; i++) {
            sum += arr[i];
        }
 
        if (sum % k != 0) {
            count++;
        }
        // Calculate the sum of rest of
        // the windows of size len
        for (i = len; i < n; i++) {
            sum = sum + arr[i];
            sum = sum - arr[i - len];
            if (sum % k != 0) {
                count++;
            }
        }
        return count;
    }
}
 
// Driver Code
int main()
{
    int arr[] = { 3, 2, 2, 2, 3 };
    int n = sizeof(arr)
            / sizeof(arr[0]);
    int k = 3;
    cout << CountLongestSubarrays(arr, n, k);
    return 0;
}
 
 

Java




// Java program for the above problem
import java.util.*;
 
class GFG{
 
// Function to find the count of
// longest subarrays with sum not
// divisible by K
static int CountLongestSubarrays(int arr[],
                                int n, int k)
{
     
    // Sum of all elements in
    // an array
    int i, s = 0;
    for(i = 0; i < n; ++i)
    {
    s += arr[i];
    }
 
    // If overall sum is not
    // divisible then return
    // 1, as only one subarray
    // of size n is possible
    if ((s % k) != 0)
    {
        return 1;
    }
    else
    {
        int ini = 0;
 
        // Index of the first number
        // not divisible by K
        while (ini < n && arr[ini] % k == 0)
        {
            ++ini;
        }
 
        int fin = n - 1;
 
        // Index of the last number
        // not divisible by K
        while (fin >= 0 && arr[fin] % k == 0)
        {
            --fin;
        }
 
        int len, sum = 0, count = 0;
         
        // Subarray doesn't exist
        if (ini == n)
        {
            return -1;
        }
        else
        {
            len = Math.max(n - 1 - ini, fin);
        }
 
        // Sum of the window
        for(i = 0; i < len; i++)
        {
        sum += arr[i];
        }
 
        if (sum % k != 0)
        {
            count++;
        }
         
        // Calculate the sum of rest of
        // the windows of size len
        for(i = len; i < n; i++)
        {
        sum = sum + arr[i];
        sum = sum - arr[i - len];
        if (sum % k != 0)
        {
            count++;
        }
        }
        return count;
    }
}
 
// Driver Code
public static void main (String []args)
{
    int arr[] = { 3, 2, 2, 2, 3 };
    int n = arr.length;
    int k = 3;
     
    System.out.print(CountLongestSubarrays(
                    arr, n, k));
}
}
 
// This code is contributed by chitranayal
 
 

Python3




# Python3 program for the above problem
 
# Function to find the count of
# longest subarrays with sum not
# divisible by K
def CountLongestSubarrays(arr, n, k):
 
    # Sum of all elements in
    # an array
    s = 0
    for i in range(n):
        s += arr[i]
 
    # If overall sum is not
    # divisible then return
    # 1, as only one subarray
    # of size n is possible
    if(s % k):
        return 1
    else:
        ini = 0
 
        # Index of the first number
        # not divisible by K
        while (ini < n and arr[ini] % k == 0):
            ini += 1
        final = n - 1
 
        # Index of the last number
        # not divisible by K
        while (final >= 0 and arr[final] % k == 0):
            final -= 1
             
        sum, count = 0, 0
         
        # Subarray doesn't exist
        if(ini == n):
            return -1
        else:
            length = max(n - 1 - ini, final)
 
        # Sum of the window
        for i in range(length):
            sum += arr[i]
 
        if(sum % k != 0):
            count += 1
 
        # Calculate the sum of rest of
        # the windows of size len
        for i in range(length, n):
            sum = sum + arr[i]
            sum = sum + arr[i - length]
            if (sum % k != 0):
                count += 1
 
        return count
 
# Driver Code
if __name__ == '__main__':
 
    arr = [ 3, 2, 2, 2, 3 ]
    n = len(arr)
    k = 3
 
    print(CountLongestSubarrays(arr, n, k))
     
# This code is contributed by Shivam Singh
 
 

C#




// C# program for the above problem
using System;
 
class GFG{
 
// Function to find the count of
// longest subarrays with sum not
// divisible by K
static int CountLongestSubarrays(int[] arr,
                                 int n, int k)
{
     
    // Sum of all elements in
    // an array
    int i, s = 0;
    for(i = 0; i < n; ++i)
    {
       s += arr[i];
    }
 
    // If overall sum is not
    // divisible then return
    // 1, as only one subarray
    // of size n is possible
    if ((s % k) != 0)
    {
        return 1;
    }
    else
    {
        int ini = 0;
 
        // Index of the first number
        // not divisible by K
        while (ini < n && arr[ini] % k == 0)
        {
            ++ini;
        }
 
        int fin = n - 1;
 
        // Index of the last number
        // not divisible by K
        while (fin >= 0 && arr[fin] % k == 0)
        {
            --fin;
        }
 
        int len, sum = 0, count = 0;
 
        // Subarray doesn't exist
        if (ini == n)
        {
            return -1;
        }
        else
        {
            len = Math.Max(n - 1 - ini, fin);
        }
 
        // Sum of the window
        for(i = 0; i < len; i++)
        {
           sum += arr[i];
        }
 
        if (sum % k != 0)
        {
            count++;
        }
 
        // Calculate the sum of rest of
        // the windows of size len
        for(i = len; i < n; i++)
        {
           sum = sum + arr[i];
           sum = sum - arr[i - len];
           if (sum % k != 0)
           {
               count++;
           }
        }
        return count;
    }
}
 
// Driver Code
public static void Main(String[] args)
{
    int[] arr = { 3, 2, 2, 2, 3 };
    int n = arr.Length;
    int k = 3;
 
    Console.WriteLine(CountLongestSubarrays(
                      arr, n, k));
}
}
 
// This code is contributed by jrishabh99
 
 

Javascript




<script>
 
// JavaScript program for the above problem 
 
// Function to find the count of
// longest subarrays with sum not
// divisible by K
function CountLongestSubarrays(arr, n, k)
{
     
    // Sum of all elements in
    // an array
    let i, s = 0;
    for(i = 0; i < n; ++i)
    {
        s += arr[i];
    }
 
    // If overall sum is not
    // divisible then return
    // 1, as only one subarray
    // of size n is possible
    if ((s % k) != 0)
    {
        return 1;
    }
    else
    {
        let ini = 0;
 
        // Index of the first number
        // not divisible by K
        while (ini < n && arr[ini] % k == 0)
        {
            ++ini;
        }
 
        let fin = n - 1;
 
        // Index of the last number
        // not divisible by K
        while (fin >= 0 && arr[fin] % k == 0)
        {
            --fin;
        }
 
        let len, sum = 0, count = 0;
         
        // Subarray doesn't exist
        if (ini == n)
        {
            return -1;
        }
        else
        {
            len = Math.max(n - 1 - ini, fin);
        }
 
        // Sum of the window
        for(i = 0; i < len; i++)
        {
            sum += arr[i];
        }
 
        if (sum % k != 0)
        {
            count++;
        }
         
        // Calculate the sum of rest of
        // the windows of size len
        for(i = len; i < n; i++)
        {
            sum = sum + arr[i];
            sum = sum - arr[i - len];
             
            if (sum % k != 0)
            {
                count++;
            }
        }
        return count;
    }
}
     
// Driver Code
let arr = [ 3, 2, 2, 2, 3 ];
let n = arr.length;
let k = 3;
 
document.write(CountLongestSubarrays(
                arr, n, k));
                 
// This code is contributed by sanjoy_62     
 
</script>
 
 
Output: 
2

 

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



Next Article
Longest Subarray With Sum Divisible By K
author
mayur_patil
Improve
Article Tags :
  • Arrays
  • Competitive Programming
  • DSA
  • Greedy
  • Mathematical
  • divisibility
  • Number Divisibility
  • sliding-window
  • subarray
Practice Tags :
  • Arrays
  • Greedy
  • Mathematical
  • sliding-window

Similar Reads

  • Longest subarray with sum not divisible by X
    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
    15+ min read
  • Longest Subarray With Sum Divisible By K
    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 = 3Output: 4Explanation: The subarray [7, 6, 1, 4] has sum = 18, which is divisible by 3. Inp
    10 min read
  • Count Subarrays With Sum Divisible By K
    Given an array arr[] and an integer k, the task is to count all subarrays whose sum is divisible by k. Examples: Input: arr[] = [4, 5, 0, -2, -3, 1], k = 5Output: 7Explanation: There are 7 subarrays whose sum is divisible by 5: [4, 5, 0, -2, -3, 1], [5], [5, 0], [5, 0, -2, -3], [0], [0, -2, -3] and
    9 min read
  • Subarray with no pair sum divisible by K
    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,
    13 min read
  • Count of subarrays with sum at least K
    Given an array arr[] of size N and an integer K > 0. The task is to find the number of subarrays with sum at least K.Examples: Input: arr[] = {6, 1, 2, 7}, K = 10 Output: 2 {6, 1, 2, 7} and {1, 2, 7} are the only valid subarrays.Input: arr[] = {3, 3, 3}, K = 5 Output: 3 Approach: For a fixed left
    6 min read
  • Max sum of Subarray of length N/2 where sum is divisible by N
    Given an array, arr[] of size N where N is even, the task is to find the maximum possible sum of the subarray of length N/2 where the sum is divisible by N. Examples: Input: arr[] = {2, 3, 4, 5, 6, 7}, N = 6Output:18Explanation: Here, N = 6, The maximum possible sum of a sublist of length 3 (N/2) is
    8 min read
  • Longest subarray with elements divisible by k
    Suppose you are given an array. You have to find the length of the longest subarray such that each and every element of it is divisible by k.Examples: Input : arr[] = { 1, 7, 2, 6, 8, 100, 3, 6, 16}, k=2Output : 4 Input : arr[] = { 3, 11, 22, 32, 55, 100, 1, 5}, k=5Output : 2 Approach: Initialize tw
    4 min read
  • Subset with no pair sum divisible by K
    Given an array of integer numbers, we need to find maximum size of a subset such that sum of each pair of this subset is not divisible by K. Examples : Input : arr[] = [3, 7, 2, 9, 1] K = 3 Output : 3 Maximum size subset whose each pair sum is not divisible by K is [3, 7, 1] because, 3+7 = 10, 3+1 =
    7 min read
  • Maximum count of distinct sized subarrays with given sum
    Given a binary array arr[] of N integers, the task is to find the maximum count of distinct sized subarrays such that the sum of each subarray is K. Example: Input: arr[] = {0, 1, 1 , 0}, K = 2Output: 3Explanation: The subset {{0, 1, 1, 0}, {0, 1, 1}, {1, 1}} is the subset of 3 subarrays such that t
    7 min read
  • Count Pairs with equal elements and Divisible Index Sum
    Given an array arr[] of length N and an integer k. You have to return the count of all the pairs (i, j) such that: arr[i] == arr[j]i<j(i+j) is divisible by kExamples: Input: N = 5, k = 3, arr[] = {1, 2, 3, 2, 1}Output: 2Explanation: arr[2] = arr[4] and 2<4 , (2+4) = 6 is divisible by 3.arr[1]
    5 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