Check if an array can be split into subsets of K consecutive elements | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool groupInKConsecutive ( vector < int > & arr , int K ) { map < int , int > count ; for ( int h : arr ) { ++ count [ h ] ; } for ( auto c : count ) { int cur = c . first ; int n = c . second ; if ( n > 0 ) { for ( int i = 1 ; i < K ; ++ i ) { if ( ! count . count ( cur + i ) ) { return false ; } count [ cur + i ] -= n ; if ( count [ cur + i ] < 0 ) return false ; } } } return true ; } int main ( ) { vector < int > arr = { 1 , 2 , 3 , 6 , 2 , 3 , 4 , 7 , 8 } ; int k = 3 ; if ( groupInKConsecutive ( arr , k ) ) { cout << " True " ; } else { cout << " False " ; } }