Check if an array can be split into subsets of K consecutive elements | Java Program to implement the above approach ; Function to check if a given array can be split into subsets of K consecutive elements ; Stores the frequencies of array elements ; Traverse the map ; Check if all its occurrences can be grouped into K subsets ; Traverse next K elements ; If the element is not present in the array ; If it cannot be split into required number of subsets ; Driver Code
import java . util . * ; class GFG { static boolean groupInKConsecutive ( int [ ] arr , int K ) { HashMap < Integer , Integer > count = new HashMap < Integer , Integer > ( ) ; for ( int h : arr ) { if ( count . containsKey ( h ) ) count . put ( h , count . get ( h ) + 1 ) ; else count . put ( h , 1 ) ; } for ( Map . Entry < Integer , Integer > c : count . entrySet ( ) ) { int cur = c . getKey ( ) ; int n = c . getValue ( ) ; if ( n > 0 ) { for ( int i = 1 ; i < K ; ++ i ) { if ( ! count . containsKey ( cur + i ) ) { return false ; } count . put ( cur + i , count . get ( cur + i ) - n ) ; if ( count . get ( cur + i ) < 0 ) return false ; } } } return true ; } public static void main ( String [ ] args ) { int [ ] arr = { 1 , 2 , 3 , 6 , 2 , 3 , 4 , 7 , 8 } ; int k = 3 ; if ( groupInKConsecutive ( arr , k ) ) { System . out . print ( " True " ) ; } else { System . out . print ( " False " ) ; } } }