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 Problems on Hash
  • Practice Hash
  • MCQs on Hash
  • Hashing Tutorial
  • Hash Function
  • Index Mapping
  • Collision Resolution
  • Open Addressing
  • Separate Chaining
  • Quadratic probing
  • Double Hashing
  • Load Factor and Rehashing
  • Advantage & Disadvantage
Open In App
Next Article:
Longest Subarray having Majority Elements Greater Than K
Next article icon

Length of longest subarray having frequency of every element equal to K

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

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 = 2
Output: 8
Explanation: The subarray: {5, 2, 2, 4, 6, 4, 6, 5} of length 8 has frequency of every element as 2.

Input: arr[] = {5, 5, 5, 5}, K = 3
Output: 3
Explanation: The subarray: {5, 5, 5} of length 3 has frequency of every element as 3.

 

Approach: Follow the steps below to solve the problem:

  1. Generate all possible subarrays from the given array.
  2. For each subarray, initialize two unordered maps map1 and map2, to store the frequency of each element and store the count of elements with the respective frequencies.
  3. If for any subarray, the size of map2 is equal to 1 and the frequency of the current element is K, that means every element individually appears K times in the current subarray.
  4. Finally, return the maximum size of all such subarrays.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
  
// Function to find the length of
// required maximum subarray
int max_subarray_len(int arr[],
                     int N, int K)
{
    // Initialize answer to 0
    int ans = 0;
  
    // Generate all subarrays having i as the
    // starting index and j as the ending index
    for (int i = 0; i < N; i++) {
  
        // Stores frequency of subarray elements
        unordered_map<int, int> map1;
  
        // Stores subarray elements with
        // respective frequencies
        unordered_map<int, int> map2;
  
        for (int j = i; j < N; j++) {
  
            // Stores previous
            // frequency of arr[j]
            int prev_freq;
  
            // If arr[j] hasn't
            // occurred previously
            if (map1.find(arr[j])
                == map1.end()) {
  
                // Set frequency as 0
                prev_freq = 0;
            }
  
            else {
  
                // Update previous frequency
                prev_freq = map1[arr[j]];
            }
  
            // Increasing frequency
            // of arr[j] by 1
            map1[arr[j]]++;
  
            // If frequency is stored
            if (map2.find(prev_freq)
                != map2.end()) {
  
                // If previous frequency is 1
                if (map2[prev_freq] == 1) {
  
                    // Rove previous frequency
                    map2.erase(prev_freq);
                }
                else {
  
                    // Decrease previous frequency
                    map2[prev_freq]--;
                }
            }
  
            int new_freq = prev_freq + 1;
  
            // Increment new frequency
            map2[new_freq]++;
  
            // If updated frequency is equal to K
            if (map2.size() == 1
                && (new_freq) == K) {
                ans = max(
                    ans, j - i + 1);
            }
        }
    }
  
    // Return the maximum size
    // of the subarray
    return ans;
}
  
// Driver Code
int main()
{
    // Given array arr[]
    int arr[] = { 3, 5, 2, 2, 4,
                  6, 4, 6, 5 };
  
    int K = 2;
  
    // Size of Array
    int N = sizeof(arr)
            / sizeof(arr[0]);
  
    // Function Call
    cout << max_subarray_len(
        arr, N, K);
  
    return 0;
}
 
 

Java




// Java program for the above approach
import java.util.*;
  
class GFG
{
  
// Function to find the length of
// required maximum subarray
static int max_subarray_len(int arr[],
                     int N, int K)
{
    // Initialize answer to 0
    int ans = 0;
  
    // Generate all subarrays having i as the
    // starting index and j as the ending index
    for (int i = 0; i < N; i++) 
    {
  
        // Stores frequency of subarray elements
        HashMap<Integer,Integer> map1 = new HashMap<>();
  
        // Stores subarray elements with
        // respective frequencies
        HashMap<Integer,Integer> map2 = new HashMap<>();
  
        for (int j = i; j < N; j++) 
        {
  
            // Stores previous
            // frequency of arr[j]
            int prev_freq = 0;
  
            // If arr[j] hasn't
            // occurred previously
            if (!map1.containsKey(arr[j])) 
            {
  
                // Set frequency as 0
                prev_freq = 0;
            }
  
            else 
            {
  
                // Update previous frequency
                prev_freq = map1.get(arr[j]);
            }
  
            // Increasing frequency
            // of arr[j] by 1
            if(map1.containsKey(arr[j]))
            {
                map1.put(arr[j], map1.get(arr[j]) + 1);
            }
            else
            {
                map1.put(arr[j], 1);
            }
  
            // If frequency is stored
            if (map2.containsKey(prev_freq)) 
            {
  
                // If previous frequency is 1
                if (map2.get(prev_freq) == 1)
                {
  
                    // Rove previous frequency
                    map2.remove(prev_freq);
                }
                else 
                {
  
                    // Decrease previous frequency
                    map2.put(prev_freq, map2.get(prev_freq)-1);
                      
                      
                }
            }
  
            int new_freq = prev_freq + 1;
  
            // Increment new frequency
            if(map2.containsKey(new_freq))
            {
                map2.put(new_freq, map2.get(new_freq) + 1);
            }
            else{
                map2.put(new_freq, 1);
            }
  
            // If updated frequency is equal to K
            if (map2.size() == 1
                && (new_freq) == K) {
                ans = Math.max(
                    ans, j - i + 1);
            }
        }
    }
  
    // Return the maximum size
    // of the subarray
    return ans;
}
  
// Driver Code
public static void main(String[] args)
{
    // Given array arr[]
    int arr[] = { 3, 5, 2, 2, 4,
                  6, 4, 6, 5 };
  
    int K = 2;
  
    // Size of Array
    int N = arr.length;
  
    // Function Call
    System.out.print(max_subarray_len(
        arr, N, K));
}
}
  
// This code is contributed by Rajput-Ji
 
 

Python3




# Python3 program for the above 
# approach
from collections import defaultdict
  
# Function to find the length of
# required maximum subarray
def max_subarray_len(arr, N, K):
  
    # Initialize answer to 0
    ans = 0
  
    # Generate all subarrays having
    # i as the starting index and j 
    # as the ending index
    for i in range(N):
  
        # Stores frequency of subarray 
        # elements
        map1 = defaultdict(int)
  
        # Stores subarray elements with
        # respective frequencies
        map2 = defaultdict(int)
  
        for j in range(i, N):
  
            # If arr[j] hasn't
            # occurred previously
            if (arr[j] not in map1):
  
                # Set frequency as 0
                prev_freq = 0
  
            else:
  
                # Update previous frequency
                prev_freq = map1[arr[j]]
  
            # Increasing frequency
            # of arr[j] by 1
            map1[arr[j]] += 1
  
            # If frequency is stored
            if prev_freq in map2:
  
                # If previous frequency is 1
                if (map2[prev_freq] == 1):
  
                    # Rove previous frequency
                    del map2[prev_freq]
  
                else:
  
                    # Decrease previous frequency
                    map2[prev_freq] -= 1
  
            new_freq = prev_freq + 1
  
            # Increment new frequency
            map2[new_freq] += 1
  
            # If updated frequency is equal 
            # to K
            if (len(map2) == 1 and 
               (new_freq) == K):
                ans = max(ans, j - i + 1)
                  
    # Return the maximum size
    # of the subarray
    return ans
  
# Driver Code
if __name__ == "__main__":
  
    # Given array arr[]
    arr = [3, 5, 2, 2, 4,
           6, 4, 6, 5]
  
    K = 2
  
    # Size of Array
    N = len(arr)
  
    # Function Call
    print(max_subarray_len(
          arr, N, K))
  
# This code is contributed by Chitranayal
 
 

C#




// C# program for the above approach
using System;
using System.Collections.Generic;
  
class GFG
{
  
// Function to find the length of
// required maximum subarray
static int max_subarray_len(int []arr,
                     int N, int K)
{
    // Initialize answer to 0
    int ans = 0;
  
    // Generate all subarrays having i as the
    // starting index and j as the ending index
    for (int i = 0; i < N; i++) 
    {
  
        // Stores frequency of subarray elements
        Dictionary<int,int> map1 = new Dictionary<int,int>();
  
        // Stores subarray elements with
        // respective frequencies
        Dictionary<int,int> map2 = new Dictionary<int,int>();
  
        for (int j = i; j < N; j++) 
        {
  
            // Stores previous
            // frequency of arr[j]
            int prev_freq = 0;
  
            // If arr[j] hasn't
            // occurred previously
            if (!map1.ContainsKey(arr[j])) 
            {
  
                // Set frequency as 0
                prev_freq = 0;
            }
  
            else 
            {
  
                // Update previous frequency
                prev_freq = map1[arr[j]];
            }
  
            // Increasing frequency
            // of arr[j] by 1
            if(map1.ContainsKey(arr[j]))
            {
                map1[arr[j]] = map1[arr[j]] + 1;
            }
            else
            {
                map1.Add(arr[j], 1);
            }
  
            // If frequency is stored
            if (map2.ContainsKey(prev_freq)) 
            {
  
                // If previous frequency is 1
                if (map2[prev_freq] == 1)
                {
  
                    // Rove previous frequency
                    map2.Remove(prev_freq);
                }
                else 
                {
  
                    // Decrease previous frequency
                    map2[prev_freq]= map2[prev_freq]-1;
                      
                      
                }
            }
  
            int new_freq = prev_freq + 1;
  
            // Increment new frequency
            if(map2.ContainsKey(new_freq))
            {
                map2[new_freq] = map2[new_freq] + 1;
            }
            else{
                map2.Add(new_freq, 1);
            }
  
            // If updated frequency is equal to K
            if (map2.Count == 1
                && (new_freq) == K) {
                ans = Math.Max(
                    ans, j - i + 1);
            }
        }
    }
  
    // Return the maximum size
    // of the subarray
    return ans;
}
  
// Driver Code
public static void Main(String[] args)
{
    // Given array []arr
    int []arr = { 3, 5, 2, 2, 4,
                  6, 4, 6, 5 };
  
    int K = 2;
  
    // Size of Array
    int N = arr.Length;
  
    // Function Call
    Console.Write(max_subarray_len(
        arr, N, K));
}
}
  
// This code is contributed by 29AjayKumar
 
 

Javascript




<script>
// Javascript program for the above approach
  
  
// Function to find the length of
// required maximum subarray
function max_subarray_len(arr,N,K)
{
    // Initialize answer to 0
    let ans = 0;
   
    // Generate all subarrays having i as the
    // starting index and j as the ending index
    for (let i = 0; i < N; i++)
    {
   
        // Stores frequency of subarray elements
        let map1 = new Map();
   
        // Stores subarray elements with
        // respective frequencies
        let map2 = new Map();
   
        for (let j = i; j < N; j++)
        {
   
            // Stores previous
            // frequency of arr[j]
            let prev_freq = 0;
   
            // If arr[j] hasn't
            // occurred previously
            if (!map1.has(arr[j]))
            {
   
                // Set frequency as 0
                prev_freq = 0;
            }
   
            else
            {
   
                // Update previous frequency
                prev_freq = map1.get(arr[j]);
            }
   
            // Increasing frequency
            // of arr[j] by 1
            if(map1.has(arr[j]))
            {
                map1.set(arr[j], map1.get(arr[j]) + 1);
            }
            else
            {
                map1.set(arr[j], 1);
            }
   
            // If frequency is stored
            if (map2.has(prev_freq))
            {
   
                // If previous frequency is 1
                if (map2.get(prev_freq) == 1)
                {
   
                    // Rove previous frequency
                    map2.delete(prev_freq);
                }
                else
                {
   
                    // Decrease previous frequency
                    map2.set(prev_freq, map2.get(prev_freq)-1);
                       
                       
                }
            }
   
            let new_freq = prev_freq + 1;
   
            // Increment new frequency
            if(map2.has(new_freq))
            {
                map2.set(new_freq, map2.get(new_freq) + 1);
            }
            else
            {
                map2.set(new_freq, 1);
            }
   
            // If updated frequency is equal to K
            if (map2.size == 1
                && (new_freq) == K) 
            {
                ans = Math.max(
                    ans, j - i + 1);
            }
        }
    }
   
    // Return the maximum size
    // of the subarray
    return ans;
}
  
// Driver Code
let arr=[ 3, 5, 2, 2, 4,
                  6, 4, 6, 5 ];
                    
let K = 2;
// Size of Array
let N = arr.length;
  
// Function Call
document.write(max_subarray_len(
arr, N, K));
  
      
  
// This code is contributed by rag2127
</script>
 
 
Output: 
8

 

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

Related Topic: Subarrays, Subsequences, and Subsets in Array



Next Article
Longest Subarray having Majority Elements Greater Than K
author
supratik_mitra
Improve
Article Tags :
  • Arrays
  • DSA
  • Hash
  • cpp-unordered_map
  • frequency-counting
  • subarray
Practice Tags :
  • Arrays
  • Hash

Similar Reads

  • Length of Longest Subarray having at Most K Frequency
    Given an integer array arr[]and an integer K, the task is to find the length of the longest subarray such that the frequency of each element is less than or equal to K. Examples: Input: arr[] = {10, 20, 30, 10, 20, 30, 10, 20}, K = 2Output: 6Explanation: The longest possible subarray is {10, 20, 30,
    5 min read
  • Longest subarray with elements having equal modulo K
    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,
    10 min read
  • Longest sub-string having frequency of each character less than equal to k
    Given a string str of length n. The problem is to find the length of the longest sub-string in str having frequency of each character less than equal to the given value k. Examples : Input : str = "babcaag", k = 1 Output : 3 abc and bca are the two longest sub-strings having frequency of each charac
    10 min read
  • Length of the longest Subarray with only Even Elements
    Given an array arr[]. The task is to find the length of the longest subarray of arr[] such that it contains only even elements. Examples: Input : arr[] = [5, 2, 4, 7]Output : 2Explanation: Subarray [2, 4] is the longest subarray containing only even elements. Input : arr[] = [9, 8, 5, 4, 4, 4, 2, 4,
    7 min read
  • 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
  • Length of Longest Subarray with same elements in atmost K increments
    Given an integer array arr and a number K, the task is to find the length of the longest subarray such that all the elements in this subarray can be made the same in atmost K increments. Examples: Input: arr[] = {2, 0, 4, 6, 7}, K = 6 Output: 3 The longest subarray is {2, 0, 4} which can be made as
    15+ min read
  • Find the length of Longest increasing Consecutive Subarray
    Given an array arr[] of N integers, the task is to find the length of the longest increasing subarray such that elements in the subarray are consecutive integers. Examples: Input: arr[] = {1, 9, 3, 4, 20, 2}Output: 2Explanation: The subarray {3, 4} is the longest subarray of consecutive elements Inp
    4 min read
  • Make sum of all subarrays of length K equal by only inserting elements
    Given an array arr[] of length N such that (1 <= arr[i] <= N), the task is to modify the array, by only inserting elements within the range [1, N], such that the sum of all subarrays of length K become equal. Print the modified array, if possible. Else print "Not possible".Examples: Input: arr
    7 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
  • 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
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