Check if an array can be split into subsets of K consecutive elements | Python3 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
from collections import defaultdict NEW_LINE def groupInKConsecutive ( arr , K ) : NEW_LINE INDENT count = defaultdict ( int ) NEW_LINE for h in arr : NEW_LINE INDENT count [ h ] += 1 NEW_LINE DEDENT for key , value in count . items ( ) : NEW_LINE INDENT cur = key NEW_LINE n = value NEW_LINE if ( n > 0 ) : NEW_LINE INDENT for i in range ( 1 , K ) : NEW_LINE INDENT if ( ( cur + i ) not in count ) : NEW_LINE INDENT return False NEW_LINE DEDENT count [ cur + i ] -= n NEW_LINE if ( count [ cur + i ] < 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT DEDENT DEDENT return True NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 6 , 2 , 3 , 4 , 7 , 8 ] NEW_LINE k = 3 NEW_LINE if ( groupInKConsecutive ( arr , k ) ) : NEW_LINE INDENT print ( " True " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " False " ) NEW_LINE DEDENT DEDENT