Split an array into equal length subsequences consisting of equal elements only | Java program for the above approach ; Function to find the GCD of two numbers a and b ; Function to check if it is possible to split the array into equal length subsequences such that all elements in the subsequence are equal ; Store frequencies of array elements ; Traverse the array ; Update frequency of arr [ i ] ; Store the GCD of frequencies of all array elements ; Traverse the map ; update gcd ; If the GCD is greater than 1 , print YES otherwise print NO ; Driver Code ; Given array ; Store the size of the array
import java . io . * ; import java . lang . * ; import java . util . * ; class GFG { int gcd ( int a , int b ) { if ( b == 0 ) return a ; return gcd ( b , a % b ) ; } void splitArray ( int arr [ ] , int N ) { TreeMap < Integer , Integer > mp = new TreeMap < Integer , Integer > ( ) ; for ( int i = 0 ; i < N ; i ++ ) { if ( mp . containsKey ( arr [ i ] ) ) { mp . put ( arr [ i ] , mp . get ( arr [ i ] ) + 1 ) ; } else { mp . put ( arr [ i ] , 1 ) ; } } int G = 0 ; for ( Map . Entry < Integer , Integer > m : mp . entrySet ( ) ) { Integer i = m . getValue ( ) ; G = gcd ( G , i . intValue ( ) ) ; } if ( G > 1 ) System . out . print ( " YES " ) ; else System . out . print ( " NO " ) ; } public static void main ( String [ ] args ) { int [ ] arr = new int [ ] { 1 , 2 , 3 , 4 , 4 , 3 , 2 , 1 } ; int n = arr . length ; new GFG ( ) . splitArray ( arr , n ) ; } }