Check if an array can be split into subsets of K consecutive elements | 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
function groupInKConsecutive ( arr , K ) { var count = new Map ( ) ; arr . forEach ( element => { if ( count . has ( element ) ) count . set ( element , count . get ( element ) + 1 ) else count . set ( element , 1 ) } ) ; count . forEach ( ( value , key ) => { var cur = key ; var n = value ; if ( n > 0 ) { for ( var i = 1 ; i < K ; ++ i ) { if ( ! count . has ( cur + i ) ) { return false ; } count . set ( cur + i , count . get ( cur + i ) - n ) ; if ( count . get ( cur + i ) < 0 ) return false ; } } } ) ; return true ; } var arr = [ 1 , 2 , 3 , 6 , 2 , 3 , 4 , 7 , 8 ] ; var k = 3 ; if ( groupInKConsecutive ( arr , k ) ) { document . write ( " " ) ; } else { document . write ( " " ) ; }