Related Articles

Related Articles

Largest subarray with frequency of all elements same
  • Last Updated : 15 Jan, 2021

Given an array arr[] of N integers, the task is to find the size of the largest subarray with frequency of all elements the same.

Examples: 

Input: arr[] = {1, 2, 2, 5, 6, 5, 6} 
Output:
Explanation: 
The subarray = {2, 2, 5, 6, 5, 6} has frequency of every element is 2.

Input: arr[] = {1, 1, 1, 1, 1} 
Output:
Explanation: 
The subarray = {1, 1, 1, 1, 1} has frequency of every element is 5.

Approach: The idea is to generate all possible subarrays and check for each subarray whether any subarray has frequency of all elements or not. Below are the steps:



  1. Generate all possible subarrays.
  2. For each subarray, take two maps, one map to stores the frequency of every element and second map stores number of elements with given frequency.
  3. If for any subarray, size of second map becomes equal to 1, that means every element have same frequency in the subarray.
  4. Return the maximum size of all such subarrays.

Below is the implementation of above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program for the above approach
 
#include <iostream>
#include <unordered_map>
using namespace std;
 
// Function to find maximum subarray size
int max_subarray_size(int N, int arr[])
{
    int ans = 0;
 
    // Generating all subarray
    // i -> starting index
    // j -> end index
    for (int i = 0; i < N; i++)
    {
        // Map 1 to hash frequency
        // of all elements in subarray
        unordered_map<int, int> map1;
 
        // Map 2 to hash frequency
        // of all frequencies of
        // elements
        unordered_map<int, int> map2;
 
        for (int j = i; j < N; j++)
        {
            // ele_count is the previous
            // frequency of arr[j]
            int ele_count;
 
            // Finding previous frequency of
            // arr[j] in map 1
            if (map1.find(arr[j]) == map1.end())
            {
                ele_count = 0;
            }
            else
            {
                ele_count = map1[arr[j]];
            }
 
            // Increasing frequency of arr[j]
            // by 1
            map1[arr[j]]++;
 
            // Check if previous frequency
            // is present in map 2
            if (map2.find(ele_count) != map2.end())
            {
                // Delete previous frequency
                // if hash is equal to 1
                if (map2[ele_count] == 1)
                {
                    map2.erase(ele_count);
                }
                else
                {
                    // Decrement the hash of
                    // previous frequency
                    map2[ele_count]--;
                }
            }
 
            // Incrementing hash of new
            // frequency in map 2
            map2[ele_count + 1]++;
 
            // Check if map2 size is 1
            // and updating answer
            if (map2.size() == 1)
                ans = max(ans, j - i + 1);
        }
    }
 
    // Return the maximum size of subarray
    return ans;
}
 
// Driver Code
int main()
{
    // Given array arr[]
    int arr[] = { 1, 2, 2, 5, 6, 5, 6 };
 
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function Call
    cout << max_subarray_size(N, arr);
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program for the above approach
import java.util.*;
class GFG
{
 
  // Function to find maximum subarray size
  static int max_subarray_size(int N, int[] arr)
  {
    int ans = 0;
 
    // Generating all subarray
    // i -> starting index
    // j -> end index
    for(int i = 0; i < N; i++)
    {
 
      // Map 1 to hash frequency
      // of all elements in subarray
      HashMap<Integer,
      Integer> map1 = new HashMap<>();
 
      // Map 2 to hash frequency
      // of all frequencies of
      // elements
      HashMap<Integer,
      Integer> map2 = new HashMap<>();
 
      for(int j = i; j < N; j++)
      {
 
        // ele_count is the previous
        // frequency of arr[j]
        int ele_count;
 
        // Finding previous frequency of
        // arr[j] in map 1
        if (!map1.containsKey(arr[j]))
        {
          ele_count = 0;
        }
        else
        {
          ele_count = 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);
        }
 
        // Check if previous frequency
        // is present in map 2
        if (map2.containsKey(ele_count))
        {
 
          // Delete previous frequency
          // if hash is equal to 1
          if (map2.get(ele_count) == 1)
          {
            map2.remove(ele_count);
          }
          else
          {
 
            // Decrement the hash of
            // previous frequency
            map2.put(ele_count,map2.get(ele_count) - 1);
          }
        }
 
        // Incrementing hash of new
        // frequency in map 2
        if (map2.containsKey(ele_count + 1))
        {
          map2.put(ele_count + 1, map2.get(ele_count + 1) + 1);
        }
        else
        {
          map2.put(ele_count + 1, 1);
        }
 
        // Check if map2 size is 1
        // and updating answer
        if (map2.size() == 1)
          ans = Math.max(ans, j - i + 1);
      }
    }
 
    // Return the maximum size of subarray
    return ans;
  }
 
  // Driver Code
  public static void main(String []args)
  {
 
    // Given array arr[]
    int[] arr = { 1, 2, 2, 5, 6, 5, 6 };
    int N = arr.length;
 
    // Function Call
    System.out.println(max_subarray_size(N, arr));
  }
}
 
// This code is contributed by rutvik_56.

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program for the above approach
 
# Function to find maximum subarray size
def max_subarray_size(N, arr):
 
    ans = 0
 
    # Generating all subarray
    # i -> starting index
    # j -> end index
    for i in range(N):
         
        # Map 1 to hash frequency
        # of all elements in subarray
        map1 = {}
 
        # Map 2 to hash frequency
        # of all frequencies of
        # elements
        map2 = {}
 
        for j in range(i, N):
         
            # ele_count is the previous
            # frequency of arr[j]
 
            # Finding previous frequency of
            # arr[j] in map 1
            if (arr[j] not in map1):
                ele_count = 0
            else:
                ele_count = map1[arr[j]]
 
            # Increasing frequency of arr[j]
            # by 1
            if arr[j] in map1:
                map1[arr[j]] += 1
            else:
                map1[arr[j]] = 1
 
            # Check if previous frequency
            # is present in map 2
            if (ele_count in map2):
         
                # Delete previous frequency
                # if hash is equal to 1
                if (map2[ele_count] == 1):
                    del map2[ele_count]
                else:
                 
                    # Decrement the hash of
                    # previous frequency
                    map2[ele_count] -= 1
 
            # Incrementing hash of new
            # frequency in map 2
            if ele_count + 1 in map2:
                map2[ele_count + 1] += 1
            else:
                map2[ele_count + 1] = 1
 
            # Check if map2 size is 1
            # and updating answer
            if (len(map2) == 1):
                ans = max(ans, j - i + 1)
 
    # Return the maximum size of subarray
    return ans
 
# Driver Code
 
# Given array arr[]
arr = [ 1, 2, 2, 5, 6, 5, 6 ]
 
N = len(arr)
 
# Function Call
print(max_subarray_size(N, arr))
 
# This code is contributed by divyeshrabadiya07

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG{
     
// Function to find maximum subarray size
static int max_subarray_size(int N, int[] arr)
{
    int ans = 0;
     
    // Generating all subarray
    // i -> starting index
    // j -> end index
    for(int i = 0; i < N; i++)
    {
         
        // Map 1 to hash frequency
        // of all elements in subarray
        Dictionary<int,
                   int> map1 = new Dictionary<int,
                                              int>();
  
        // Map 2 to hash frequency
        // of all frequencies of
        // elements
        Dictionary<int,
                   int> map2 = new Dictionary<int,
                                              int>();
  
        for(int j = i; j < N; j++)
        {
             
            // ele_count is the previous
            // frequency of arr[j]
            int ele_count;
  
            // Finding previous frequency of
            // arr[j] in map 1
            if (!map1.ContainsKey(arr[j]))
            {
                ele_count = 0;
            }
            else
            {
                ele_count = map1[arr[j]];
            }
  
            // Increasing frequency of arr[j]
            // by 1
            if (map1.ContainsKey(arr[j]))
            {
                map1[arr[j]]++;
            }
            else
            {
                map1.Add(arr[j], 1);
            }
  
            // Check if previous frequency
            // is present in map 2
            if (map2.ContainsKey(ele_count))
            {
                 
                // Delete previous frequency
                // if hash is equal to 1
                if (map2[ele_count] == 1)
                {
                    map2.Remove(ele_count);
                }
                else
                {
                     
                    // Decrement the hash of
                    // previous frequency
                    map2[ele_count]--;
                }
            }
  
            // Incrementing hash of new
            // frequency in map 2
            if (map2.ContainsKey(ele_count + 1))
            {
                map2[ele_count + 1]++;
            }
            else
            {
                map2.Add(ele_count + 1, 1);
            }
  
            // Check if map2 size is 1
            // and updating answer
            if (map2.Count == 1)
                ans = Math.Max(ans, j - i + 1);
        }
    }
  
    // Return the maximum size of subarray
    return ans;
}
 
// Driver Code
static void Main()
{
     
    // Given array arr[]
    int[] arr = { 1, 2, 2, 5, 6, 5, 6 };
  
    int N = arr.Length;
  
    // Function Call
    Console.WriteLine(max_subarray_size(N, arr));
}
}
 
// This code is contributed by divyesh072019

chevron_right


Output:

6

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

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up
Recommended Articles
Page :