Largest subarray with frequency of all elements same
Last Updated :
14 Feb, 2023
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: 6
Explanation:
The subarray = {2, 2, 5, 6, 5, 6} has frequency of every element is 2.
Input: arr[] = {1, 1, 1, 1, 1}
Output: 5
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:
- Generate all possible subarrays.
- 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.
- If for any subarray, size of second map becomes equal to 1, that means every element have same frequency in the subarray.
- Return the maximum size of all such subarrays.
Below is the implementation of above approach:
C++
#include <iostream>
#include <unordered_map>
using namespace std;
int max_subarray_size( int N, int arr[])
{
int ans = 0;
for ( int i = 0; i < N; i++)
{
unordered_map< int , int > map1;
unordered_map< int , int > map2;
for ( int j = i; j < N; j++)
{
int ele_count;
if (map1.find(arr[j]) == map1.end())
{
ele_count = 0;
}
else
{
ele_count = map1[arr[j]];
}
map1[arr[j]]++;
if (map2.find(ele_count) != map2.end())
{
if (map2[ele_count] == 1)
{
map2.erase(ele_count);
}
else
{
map2[ele_count]--;
}
}
map2[ele_count + 1]++;
if (map2.size() == 1)
ans = max(ans, j - i + 1);
}
}
return ans;
}
int main()
{
int arr[] = { 1, 2, 2, 5, 6, 5, 6 };
int N = sizeof (arr) / sizeof (arr[0]);
cout << max_subarray_size(N, arr);
return 0;
}
|
Java
import java.util.*;
class GFG
{
static int max_subarray_size( int N, int [] arr)
{
int ans = 0 ;
for ( int i = 0 ; i < N; i++)
{
HashMap<Integer,
Integer> map1 = new HashMap<>();
HashMap<Integer,
Integer> map2 = new HashMap<>();
for ( int j = i; j < N; j++)
{
int ele_count;
if (!map1.containsKey(arr[j]))
{
ele_count = 0 ;
}
else
{
ele_count = map1.get(arr[j]);
}
if (map1.containsKey(arr[j]))
{
map1.put(arr[j],map1.get(arr[j])+ 1 );
}
else
{
map1.put(arr[j], 1 );
}
if (map2.containsKey(ele_count))
{
if (map2.get(ele_count) == 1 )
{
map2.remove(ele_count);
}
else
{
map2.put(ele_count,map2.get(ele_count) - 1 );
}
}
if (map2.containsKey(ele_count + 1 ))
{
map2.put(ele_count + 1 , map2.get(ele_count + 1 ) + 1 );
}
else
{
map2.put(ele_count + 1 , 1 );
}
if (map2.size() == 1 )
ans = Math.max(ans, j - i + 1 );
}
}
return ans;
}
public static void main(String []args)
{
int [] arr = { 1 , 2 , 2 , 5 , 6 , 5 , 6 };
int N = arr.length;
System.out.println(max_subarray_size(N, arr));
}
}
|
Python3
def max_subarray_size(N, arr):
ans = 0
for i in range (N):
map1 = {}
map2 = {}
for j in range (i, N):
if (arr[j] not in map1):
ele_count = 0
else :
ele_count = map1[arr[j]]
if arr[j] in map1:
map1[arr[j]] + = 1
else :
map1[arr[j]] = 1
if (ele_count in map2):
if (map2[ele_count] = = 1 ):
del map2[ele_count]
else :
map2[ele_count] - = 1
if ele_count + 1 in map2:
map2[ele_count + 1 ] + = 1
else :
map2[ele_count + 1 ] = 1
if ( len (map2) = = 1 ):
ans = max (ans, j - i + 1 )
return ans
arr = [ 1 , 2 , 2 , 5 , 6 , 5 , 6 ]
N = len (arr)
print (max_subarray_size(N, arr))
|
C#
using System;
using System.Collections.Generic;
class GFG{
static int max_subarray_size( int N, int [] arr)
{
int ans = 0;
for ( int i = 0; i < N; i++)
{
Dictionary< int ,
int > map1 = new Dictionary< int ,
int >();
Dictionary< int ,
int > map2 = new Dictionary< int ,
int >();
for ( int j = i; j < N; j++)
{
int ele_count;
if (!map1.ContainsKey(arr[j]))
{
ele_count = 0;
}
else
{
ele_count = map1[arr[j]];
}
if (map1.ContainsKey(arr[j]))
{
map1[arr[j]]++;
}
else
{
map1.Add(arr[j], 1);
}
if (map2.ContainsKey(ele_count))
{
if (map2[ele_count] == 1)
{
map2.Remove(ele_count);
}
else
{
map2[ele_count]--;
}
}
if (map2.ContainsKey(ele_count + 1))
{
map2[ele_count + 1]++;
}
else
{
map2.Add(ele_count + 1, 1);
}
if (map2.Count == 1)
ans = Math.Max(ans, j - i + 1);
}
}
return ans;
}
static void Main()
{
int [] arr = { 1, 2, 2, 5, 6, 5, 6 };
int N = arr.Length;
Console.WriteLine(max_subarray_size(N, arr));
}
}
|
Javascript
<script>
function max_subarray_size(N, arr)
{
let ans = 0;
for (let i = 0; i < N; i++)
{
let map1 = new Map();
let map2 = new Map();
for (let j = i; j < N; j++)
{
let ele_count;
if (!map1.has(arr[j]))
{
ele_count = 0;
}
else
{
ele_count = map1.get(arr[j]);
}
map1.set(arr[j],ele_count+1)
if (map2.has(ele_count))
{
if (map2.get(ele_count) == 1)
{
map2. delete (ele_count);
}
else
{
map2.set(ele_count,map2.get(ele_count)-1)
}
}
if (map2.get(ele_count+1) !== undefined){
map2.set(ele_count+1,map2.get(ele_count+1)+1);
}
else map2.set(ele_count+1,1);
if (map2.size == 1){
ans = Math.max(ans, j - i + 1);
}
}
}
return ans;
}
const arr = [ 1, 2, 2, 5, 6, 5, 6 ];
const N = arr.length;
document.write(max_subarray_size(N, arr));
</script>
|
Time Complexity: O(N2)
Auxiliary Space: O(N)
Naive Approach: Simple solution is to generate all subarrays and check whether each element has same frequency or not.
C++14
#include <bits/stdc++.h>
using namespace std;
int ans=1;
int checkFreq( int *arr, int r, int l)
{
int i,count=1;
vector< int >temp;
vector< int >freq;
freq.clear();
temp.clear();
for (i=r;i<=l;i++)
temp.push_back(arr[i]);
sort(temp.begin(),temp.end());
for (i=0;i<temp.size();i++)
{
if (temp[i]==temp[i+1])
count++;
else {
freq.push_back(count);
count=1;
}
}
for (i=1;i<freq.size();i++)
{
if (freq[0]!=freq[i])
return -1;
}
return temp.size();
}
void generateSubArrays( int *arr, int start, int end, int len)
{
if (end==len)
return ;
else if (start>end)
generateSubArrays(arr,0,end+1,len);
else {
ans=max(ans,checkFreq(arr,start,end));
generateSubArrays(arr,start+1,end,len);
}
}
int main()
{
int arr[]={ 1, 10, 5, 4, 4, 4, 10 };
int n= sizeof (arr)/ sizeof (arr[0]);
generateSubArrays(arr,0,0,n);
cout<<ans;
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class GFG
{
static int ans = 1 ;
static int checkFreq( int arr[], int r, int l)
{
int i, count = 1 ;
ArrayList<Integer> temp = new ArrayList<>();
ArrayList<Integer> freq = new ArrayList<>();
for (i = r; i <= l; i++)
temp.add(arr[i]);
Collections.sort(temp);
for (i = 0 ; i < temp.size()- 1 ; i++)
{
if (temp.get(i) == temp.get(i+ 1 ))
count++;
else {
freq.add(count);
count= 1 ;
}
}
for (i = 1 ; i < freq.size(); i++)
{
if (freq.get( 0 ) != freq.get(i))
return - 1 ;
}
return temp.size();
}
static void generateSubArrays( int arr[], int start, int end, int len)
{
if (end == len)
return ;
else if (start > end)
generateSubArrays(arr, 0 , end + 1 , len);
else {
ans = Math.max(ans, checkFreq(arr, start, end));
generateSubArrays(arr, start + 1 , end, len);
}
}
public static void main(String args[])
{
int arr[] = { 1 , 10 , 5 , 4 , 4 , 4 , 10 };
int n = arr.length;
generateSubArrays(arr, 0 , 0 ,n);
System.out.println(ans);
}
}
|
Python3
from pickle import GLOBAL
ans = 1
def checkFreq(arr, r, l):
i, count = 1 , 1
temp = []
freq = []
freq.clear()
temp.clear()
for i in range (r, l + 1 ):
temp.append(arr[i])
temp.sort()
for i in range ( len (temp) - 1 ):
if (temp[i] = = temp[i + 1 ]):
count + = 1
else :
freq.append(count)
count = 1
for i in range ( 1 , len (freq)):
if (freq[ 0 ] ! = freq[i]):
return - 1
return len (temp)
def generateSubArrays(arr, start, end, Len ):
global ans
if (end = = Len ):
return
elif (start > end):
generateSubArrays(arr, 0 , end + 1 , Len )
else :
ans = max (ans,checkFreq(arr, start, end))
generateSubArrays(arr, start + 1 , end, Len )
arr = [ 1 , 10 , 5 , 4 , 4 , 4 , 10 ]
n = len (arr)
generateSubArrays(arr, 0 , 0 , n)
print (ans)
|
C#
using System;
using System.Collections.Generic;
public static class GFG {
public static int ans = 1;
public static int checkFreq( int [] arr, int r, int l)
{
int i, count = 1;
List< int > temp = new List< int >();
List< int > freq = new List< int >();
for (i = r; i <= l; i++)
temp.Add(arr[i]);
temp.Sort();
for (i = 0; i < temp.Count - 1; i++) {
if (temp[i] == temp[i + 1])
count++;
else {
freq.Add(count);
count = 1;
}
}
for (i = 1; i < freq.Count; i++) {
if (freq[0] != freq[i])
return -1;
}
return temp.Count;
}
public static void generateSubArrays( int [] arr,
int start, int end,
int len)
{
if (end == len)
return ;
else if (start > end)
generateSubArrays(arr, 0, end + 1, len);
else {
ans = Math.Max(ans, checkFreq(arr, start, end));
generateSubArrays(arr, start + 1, end, len);
}
}
static public void Main()
{
int [] arr = { 1, 10, 5, 4, 4, 4, 10 };
int n = arr.Length;
generateSubArrays(arr, 0, 0, n);
Console.WriteLine(ans);
}
}
|
Javascript
<script>
let ans=1;
function checkFreq(arr,r,l)
{
let i,count=1;
let temp = [];
let freq = [];
for (i=r;i<=l;i++)
temp.push(arr[i]);
temp.sort();
for (i=0;i<temp.length;i++)
{
if (temp[i]==temp[i+1])
count++;
else {
freq.push(count);
count=1;
}
}
for (i=1;i<freq.length;i++)
{
if (freq[0]!=freq[i])
return -1;
}
return temp.length;
}
function generateSubArrays(arr,start,end,len)
{
if (end==len)
return ;
else if (start>end)
generateSubArrays(arr,0,end+1,len);
else {
ans=Math.max(ans,checkFreq(arr,start,end));
generateSubArrays(arr,start+1,end,len);
}
}
let arr = [ 1, 10, 5, 4, 4, 4, 10 ];
let n = arr.length;
generateSubArrays(arr,0,0,n);
console.log(ans);
</script>
|
Output:
4
Time Complexity: O(n^3 log n)
Auxiliary Space: O(n)
Efficient solution: Another efficient way is to store frequencies of all elements in a map consecutively and check its frequency each time with starting of the map.
C++
#include <bits/stdc++.h>
using namespace std;
int longestSubArray( int a[], int n){
int i;
int ans = 1;
for ( int i = 0; i < n; i++) {
map < int , int > mp;
for ( int j = i; j < n; j++) {
mp[a[j]] = mp[a[j]] + 1;
bool ok = true ;
int count = mp.begin() -> second;
for (map < int , int > :: iterator it = mp.begin(); it!= mp.end(); ++it) {
if (count != it -> second) {
ok = false ;
break ;
}
}
if (ok) {
ans = max(ans, j - i + 1);
}
}
}
return ans;
}
int main()
{
int arr[]={1,2,8,8,4,4};
int n= sizeof (arr)/ sizeof (arr[0]);
cout<<longestSubArray(arr,n);
}
|
Java
import java.io.*;
import java.util.*;
class GFG {
static int longestSubArray( int a[], int n){
int i;
int ans = 1 ;
for (i = 0 ; i < n; i++)
{
TreeMap <Integer, Integer> mp = new TreeMap<>();
for ( int j = i; j < n; j++)
{
if (mp.containsKey(a[j])){
mp.put(a[j],mp.get(a[j])+ 1 );
}
else mp.put(a[j], 1 );
Boolean ok = true ;
int count = mp.firstEntry().getValue();
for (Map.Entry mapEl : mp.entrySet()) {
if (count != ( int )mapEl.getValue()) {
ok = false ;
break ;
}
}
if (ok)
{
ans = Math.max(ans, j - i + 1 );
}
}
}
return ans;
}
public static void main(String args[])
{
int arr[] = { 1 , 2 , 8 , 8 , 4 , 4 };
int n = arr.length;
System.out.println(longestSubArray(arr, n));
}
}
|
Python3
def longestSubArray(a,n):
ans = 1
for i in range (n):
mp = {}
for j in range (i,n):
if a[j] in mp:
mp[a[j]] + = 1
else :
mp[a[j]] = 1
ok = True
count = list (mp.values())[ 0 ]
for it in mp.values():
if count ! = it:
ok = False
break
if ok:
ans = max (ans, j - i + 1 )
return ans
arr = [ 1 , 2 , 8 , 8 , 4 , 4 ]
n = len (arr)
print (longestSubArray(arr,n))
|
C#
using System;
using System.Collections.Generic;
using System.Linq;
public class GFG
{
public static int longestSubArray( int [] a, int n)
{
int i;
var ans = 1;
for (i = 0; i < n; i++)
{
var mp = new SortedDictionary< int , int >();
for ( int j = i; j < n; j++)
{
if (mp.ContainsKey(a[j]))
{
mp[a[j]] = mp[a[j]] + 1;
}
else
{
mp[a[j]] = 1;
}
var ok = true ;
var count = mp[mp.Keys.Min()];
foreach ( var key in mp.Keys.ToList())
{
if (count != ( int )mp[key])
{
ok = false ;
break ;
}
}
if (ok)
{
ans = Math.Max(ans,j - i + 1);
}
}
}
return ans;
}
public static void Main(String[] args)
{
int [] arr = {1, 2, 8, 8, 4, 4};
var n = arr.Length;
Console.WriteLine(GFG.longestSubArray(arr, n));
}
}
|
Javascript
const longestSubArray = (a, n) => {
let i;
let ans = 1;
for (let i = 0; i < n; i++) {
let mp = {};
for (let j = i; j < n; j++)
{
mp[a[j]] = mp[a[j]] + 1 || 1;
let ok = true ;
let count = Object.values(mp)[0];
for (let it in mp) {
if (count !== mp[it]) {
ok = false ;
break ;
}
}
if (ok) {
ans = Math.max(ans, j - i + 1);
}
}
}
return ans;
};
const arr = [1, 2, 8, 8, 4, 4];
const n = arr.length;
console.log(longestSubArray(arr, n));
|
Output:
4
Time Complexity: O(n^2 )
Auxiliary Space: O(n)
Related Topic: Subarrays, Subsequences, and Subsets in Array
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...