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 not having more than K distinct elements
Next article icon

Longest subarray with elements having equal modulo K

Last Updated : 09 Sep, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an integer K and an array arr of integer elements, the task is to print the length of the longest sub-array such that each element of this sub-array yields same remainder upon division by K.

Examples: 

Input: arr[] = {2, 1, 5, 8, 1}, K = 3 
Output: 2 
{2, 1, 5, 8, 1} gives remainders {2, 1, 2, 2, 1} on division with 3 
Hence, longest sub-array length is 2.

Input: arr[] = {1, 100, 2, 9, 4, 32, 6, 3}, K = 2 
Output: 3 

Simple Approach: 

  • Traverse the array from left to right and store modulo of each element with K in second array.
  • Now the task is reduced to find the longest sub-array with same elements.

Below is the implementation of the above approach:

C++




// C++ implementation of above approach
#include <bits/stdc++.h>
using namespace std;
 
// function to find longest sub-array
// whose elements gives same remainder
// when divided with K
int LongestSubarray(int arr[], int n, int k)
{
    // second array contains modulo
    // results of each element with K
    int arr2[n];
    for (int i = 0; i < n; i++)
        arr2[i] = arr[i] % k;
 
    int current_length, max_length = 0;
    int j;
 
    // loop for finding longest sub-array
    // with equal elements
    for (int i = 0; i < n;) {
        current_length = 1;
        for (j = i + 1; j < n; j++) {
            if (arr2[j] == arr2[i])
                current_length++;
            else
                break;
        }
        max_length = max(max_length, current_length);
        i = j;
    }
    return max_length;
}
 
// Driver code
int main()
{
    int arr[] = { 4, 9, 7, 18, 29, 11 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int k = 11;
    cout << LongestSubarray(arr, n, k);
    return 0;
}
 
 

Java




//  Java implementation of above approach
import java .io.*;
 
class GFG
{
// function to find longest sub-array
// whose elements gives same remainder
// when divided with K
static int LongestSubarray(int[] arr,
                        int n, int k)
{
    // second array contains modulo
    // results of each element with K
    int[] arr2 = new int[n];
    for (int i = 0; i < n; i++)
        arr2[i] = arr[i] % k;
 
    int current_length, max_length = 0;
    int j;
 
    // loop for finding longest
    // sub-array with equal elements
    for (int i = 0; i < n;)
    {
        current_length = 1;
        for (j = i + 1; j < n; j++)
        {
            if (arr2[j] == arr2[i])
                current_length++;
            else
                break;
        }
        max_length = Math.max(max_length,
                            current_length);
        i = j;
    }
    return max_length;
}
 
// Driver code
public static void main(String[] args)
{
    int[] arr = { 4, 9, 7, 18, 29, 11 };
    int n = arr.length;
    int k = 11;
    System.out.println(LongestSubarray(arr, n, k));
}
}
 
// This code is contributed
// by shs
 
 

Python 3




# Python 3 implementation of above approach
 
# function to find longest sub-array
# whose elements gives same remainder
# when divided with K
def LongestSubarray(arr, n, k):
 
    # second array contains modulo
    # results of each element with K
    arr2 = [0] * n
    for i in range( n):
        arr2[i] = arr[i] % k
         
    max_length = 0
 
    # loop for finding longest sub-array
    # with equal elements
    i = 0
    while i < n :
        current_length = 1
        for j in range(i + 1, n):
            if (arr2[j] == arr2[i]):
                current_length += 1
            else:
                break
         
        max_length = max(max_length,
                         current_length)
        i = j
        i += 1
 
    return max_length
 
# Driver code
if __name__ == "__main__":
    arr = [ 4, 9, 7, 18, 29, 11 ]
    n = len(arr)
    k = 11
    print(LongestSubarray(arr, n, k))
 
# This code is contributed
# by ChitraNayal
 
 

C#




// C# implementation of above approach
using System;
 
class GFG
{
// function to find longest sub-array
// whose elements gives same remainder
// when divided with K
static int LongestSubarray(int[] arr,
                           int n, int k)
{
    // second array contains modulo
    // results of each element with K
    int[] arr2 = new int[n];
    for (int i = 0; i < n; i++)
        arr2[i] = arr[i] % k;
 
    int current_length, max_length = 0;
    int j;
 
    // loop for finding longest
    // sub-array with equal elements
    for (int i = 0; i < n;)
    {
        current_length = 1;
        for (j = i + 1; j < n; j++)
        {
            if (arr2[j] == arr2[i])
                current_length++;
            else
                break;
        }
        max_length = Math.Max(max_length,  
                              current_length);
        i = j;
    }
    return max_length;
}
 
// Driver code
public static void Main()
{
    int[] arr = { 4, 9, 7, 18, 29, 11 };
    int n = arr.Length;
    int k = 11;
    Console.Write(LongestSubarray(arr, n, k));
}
}
 
// This code is contributed
// by Akanksha Rai
 
 

PHP




<?php
// PHP implementation of above approach
 
// function to find longest sub-array
// whose elements gives same remainder
// when divided with K
function LongestSubarray($arr, $n, $k)
{
    // second array contains modulo
    // results of each element with K
    $arr2[$n] = array();
    for ($i = 0; $i < $n; $i++)
        $arr2[$i] = $arr[$i] % $k;
 
    $current_length;
    $max_length = 0;
    $j;
 
    // loop for finding longest sub-array
    // with equal elements
    for ($i = 0; $i < $n😉
    {
        $current_length = 1;
        for ($j = $i + 1; $j < $n; $j++)
        {
            if ($arr2[$j] == $arr2[$i])
                $current_length++;
            else
                break;
        }
        $max_length = max($max_length,
                          $current_length);
        $i = $j;
    }
    return $max_length;
}
 
// Driver code
$arr = array( 4, 9, 7, 18, 29, 11 );
$n = sizeof($arr);
$k = 11;
echo LongestSubarray($arr, $n, $k);
 
// This code is contributed
// by Sach_Code
?>
 
 

Javascript




<script>
 
// Javascript implementation of above approach
 
// function to find longest sub-array
// whose elements gives same remainder
// when divided with K
function LongestSubarray(arr, n, k)
{
    // second array contains modulo
    // results of each element with K
    var arr2 = Array(n);
    for (var i = 0; i < n; i++)
        arr2[i] = arr[i] % k;
 
    var current_length, max_length = 0;
    var j;
 
    // loop for finding longest sub-array
    // with equal elements
    for (var i = 0; i < n;) {
        current_length = 1;
        for (j = i + 1; j < n; j++) {
            if (arr2[j] == arr2[i])
                current_length++;
            else
                break;
        }
        max_length = Math.max(max_length, current_length);
        i = j;
    }
    return max_length;
}
 
// Driver code
var arr = [4, 9, 7, 18, 29, 11 ];
var n = arr.length;
var k = 11;
document.write( LongestSubarray(arr, n, k));
 
</script>
 
 
Output
3

Complexity Analysis:

  • Time Complexity: O(n * n) 
  • Auxiliary Space: O(n)

An efficient approach is to keep track of the current count in a single traversal. Whenever we find an element whose modulo is not same, we reset count as 0.

Implementation: 

C++




// C++ implementation of above approach
#include <bits/stdc++.h>
using namespace std;
 
// function to find longest sub-array
// whose elements gives same remainder
// when divided with K
int LongestSubarray(int arr[], int n, int k)
{
    int count = 1;
    int max_length = 1;
    int prev_mod = arr[0] % k;
   
    // Iterate in the array
    for (int i = 1; i < n; i++) {
 
        int curr_mod = arr[i] % k;
   
        // check if array element
        // greater then X or not
        if (curr_mod == prev_mod) {
            count++;
        }
        else {
   
            max_length = max(max_length, count);  
            count = 1;
            prev_mod = curr_mod;
        }
    }
     
    return max(max_length, count);
}
 
// Driver code
int main()
{
    int arr[] = { 4, 9, 7, 18, 29, 11 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int k = 11;
    cout << LongestSubarray(arr, n, k);
    return 0;
}
 
 

Java




// Java implementation of above approach
 
class GFG {
 
// function to find longest sub-array
// whose elements gives same remainder
// when divided with K
    static public int LongestSubarray(int arr[], int n, int k) {
        int count = 1;
        int max_length = 1;
        int prev_mod = arr[0] % k;
 
        // Iterate in the array
        for (int i = 1; i < n; i++) {
 
            int curr_mod = arr[i] % k;
 
            // check if array element
            // greater then X or not
            if (curr_mod == prev_mod) {
                count++;
            } else {
 
                max_length = Math.max(max_length, count);
                count = 1;
                prev_mod = curr_mod;
            }
        }
 
        return Math.max(max_length, count);
    }
 
// Driver code
    public static void main(String[] args) {
        int arr[] = {4, 9, 7, 18, 29, 11};
        int n = arr.length;
        int k = 11;
        System.out.print(LongestSubarray(arr, n, k));
    }
}
// This code is contributed by Rajput-Ji
 
 

Python3




# Python3 implementation of above approach
 
# function to find longest sub-array
# whose elements gives same remainder
#  when divided with K
 
def LongestSubarray(arr,n,k):
    count = 1
    max_lenght = 1
    prev_mod = arr[0]%k
 
    # Iterate in the array
    for i in range(1,n):
        curr_mod = arr[i]%k
 
       #  check if array element
       # greater then X or not
        if curr_mod==prev_mod:
            count+=1
        else:
            max_lenght = max(max_lenght,count)
            count=1
            prev_mod = curr_mod
 
 
    return max(max_lenght,count)
 
# Driver code
arr = [4, 9, 7, 18, 29, 11]
n = len(arr)
k =11
print(LongestSubarray(arr,n,k))
 
 
 
# This code is contributed by Shrikant13
 
 

C#




// C# implementation of above approach
using System;
 
class GFG
{
     
// function to find longest sub-array
// whose elements gives same remainder
// when divided with K
static int LongestSubarray(int []arr, int n, int k)
{
    int count = 1;
    int max_length = 1;
    int prev_mod = arr[0] % k;
 
    // Iterate in the array
    for (int i = 1; i < n; i++)
    {
 
        int curr_mod = arr[i] % k;
 
        // check if array element
        // greater then X or not
        if (curr_mod == prev_mod)
        {
            count++;
        }
        else
        {
            max_length = Math.Max(max_length, count);
            count = 1;
            prev_mod = curr_mod;
        }
    }
    return Math.Max(max_length, count);
}
 
// Driver code
public static void Main()
{
    int[] arr = { 4, 9, 7, 18, 29, 11 };
    int n = arr.Length;
    int k = 11;
    Console.Write(LongestSubarray(arr, n, k));
}
}
 
// This code is contributed by Shivi_Aggarwal
 
 

PHP




<?php
// PHP implementation of above approach
 
// function to find longest sub-array
// whose elements gives same remainder
// when divided with K
function LongestSubarray($arr, $n, $k)
{
    $cnt = 1;
    $max_length = 1;
    $prev_mod = $arr[0] % $k;
 
    // Iterate in the array
    for ($i = 1; $i < $n; $i++)
    {
 
        $curr_mod = $arr[$i] % $k;
 
        // check if array element
        // greater then X or not
        if ($curr_mod == $prev_mod)
        {
            $cnt++;
        }
        else
        {
            $max_length = max($max_length, $cnt);
            $cnt = 1;
            $prev_mod = $curr_mod;
        }
    }
     
    return max($max_length, $cnt);
}
 
// Driver code
$arr = array( 4, 9, 7, 18, 29, 11 );
$n = count($arr) ;
$k = 11;
echo LongestSubarray($arr, $n, $k);
 
// This code is contributed by 29AjayKumar
?>
 
 

Javascript




<script>
// Javascript implementation of above approach
     
    // function to find longest sub-array
// whose elements gives same remainder
// when divided with K
    function LongestSubarray(arr,n,k)
    {
        let count = 1;
        let max_length = 1;
        let prev_mod = arr[0] % k;
  
        // Iterate in the array
        for (let i = 1; i < n; i++) {
  
            let curr_mod = arr[i] % k;
  
            // check if array element
            // greater then X or not
            if (curr_mod == prev_mod) {
                count++;
            } else {
  
                max_length = Math.max(max_length, count);
                count = 1;
                prev_mod = curr_mod;
            }
        }
  
        return Math.max(max_length, count);
    }
     
    // Driver code
    let arr = [4, 9, 7, 18, 29, 11];
    let n = arr.length;
    let k = 11;
    document.write(LongestSubarray(arr, n, k));
 
// This code is contributed by rag2127
</script>
 
 
Output
3

Complexity Analysis:

  • Time Complexity: O(n) 
  • Auxiliary Space: O(1)


Next Article
Longest subarray not having more than K distinct elements

S

Shashank_Sharma
Improve
Article Tags :
  • Arrays
  • DSA
  • Searching
  • array-traversal-question
  • Technical Scripter 2018
Practice Tags :
  • Arrays
  • Searching

Similar Reads

  • Longest Subarray having Majority Elements Greater Than K
    Given an array arr[] and an integer k, the task is to find the length of longest subarray in which the count of elements greater than k is more than the count of elements less than or equal to k. Examples: Input: arr[]= [1, 2, 3, 4, 1], k = 2Output: 3 Explanation: The subarray [2, 3, 4] or [3, 4, 1]
    13 min read
  • Longest subarray not having more than K distinct elements
    Given N elements and a number K, find the longest subarray which has not more than K distinct elements.(It can have less than K). Examples: Input : arr[] = {1, 2, 3, 4, 5} k = 6 Output : 1 2 3 4 5 Explanation: The whole array has only 5 distinct elements which is less than k, so we print the array i
    8 min read
  • Longest subarray with all even or all odd elements
    Given an array A[ ] of N non-negative integers, the task is to find the length of the longest sub-array such that all the elements in that sub-array are odd or even. Examples: Input: A[] = {2, 5, 7, 2, 4, 6, 8, 3}Output: 4Explanation: Sub-array {2, 4, 6, 8} of length 4 has all even elements Input: A
    15+ min read
  • Longest subarray having sum of elements atmost K
    Given an array arr[] of size N and an integer K, the task is to find the length of the largest subarray having the sum of its elements at most K, where K > 0. Examples: Input: arr[] = {1, 2, 1, 0, 1, 1, 0}, k = 4Output: 5Explanation: {1, 2, 1} => sum = 4, length = 3 {1, 2, 1, 0}, {2, 1, 0, 1}
    12 min read
  • Length of longest subarray having frequency of every element equal to K
    Given an array arr[] consisting of N integers and an integer K, the task is to find the length of the longest subarray such that each element occurs K times. Examples: Input: arr[] = {3, 5, 2, 2, 4, 6, 4, 6, 5}, K = 2Output: 8Explanation: The subarray: {5, 2, 2, 4, 6, 4, 6, 5} of length 8 has freque
    9 min read
  • Longest subarray in which all elements are a factor of K
    Given an array A[] of size N and a positive integer K, the task is to find the length of the longest subarray such that all elements of the subarray is a factor of K. Examples: Input: A[] = {2, 8, 3, 10, 6, 7, 4, 9}, K = 60Output: 3Explanation: The longest subarray in which all elements are a factor
    6 min read
  • Longest subarray with all elements same
    Given an array arr[] of size N, the task is to find the largest subarray which consists of all equal elements.Examples: Input: arr[] = {1, 1, 2, 2, 2, 3, 3}; Output: 3 Explanation: Longest subarray with equal elements is {2, 2, 2}Input: arr[] = {1, 1, 2, 2, 2, 3, 3, 3, 3}; Output: 4 Explanation: Lon
    4 min read
  • Longest subarray whose elements can be made equal by maximum K increments
    Given an array arr[] of positive integers of size N and a positive integer K, the task is to find the maximum possible length of a subarray which can be made equal by adding some integer value to each element of the sub-array such that the sum of the added elements does not exceed K. Examples: Input
    12 min read
  • Maximize length of subarray having equal elements by adding at most K
    Given an array arr[] consisting of N positive integers and an integer K, which represents the maximum number that can be added to the array elements. The task is to maximize the length of the longest possible subarray of equal elements by adding at most K. Examples: Input: arr[] = {3, 0, 2, 2, 1}, k
    9 min read
  • Longest subarray in which all elements are greater than K
    Given an array of N integers and a number K, the task is to find the length of the longest subarray in which all the elements are greater than K. Examples: Input: a[] = {3, 4, 5, 6, 7, 2, 10, 11}, K = 5 Output: 2 There are two possible longest subarrays of length 2. They are {6, 7} and {10, 11}. Inp
    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