Check if array elements are consecutive | Added Method 3 | Helper functions to get minimum and maximum in an array The function checks if the array elements are consecutive . If elements are consecutive , then returns true , else returns false ; 1 ) Get the minimum element in array ; 2 ) Get the maximum element in array ; 3 ) max - min + 1 is equal to n then only check all elements ; if the value at index j is negative then there is repetition ; If we do not see a negative value then all elements are distinct ; if ( max - min + 1 != n ) ; UTILITY FUNCTIONS ; Driver Code
def areConsecutive ( arr , n ) : NEW_LINE INDENT if ( n < 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT min = getMin ( arr , n ) NEW_LINE max = getMax ( arr , n ) NEW_LINE if ( max - min + 1 == n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] < 0 ) : NEW_LINE INDENT j = - arr [ i ] - min NEW_LINE DEDENT else : NEW_LINE INDENT j = arr [ i ] - min NEW_LINE DEDENT if ( arr [ j ] > 0 ) : NEW_LINE INDENT arr [ j ] = - arr [ j ] NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT def getMin ( arr , n ) : NEW_LINE INDENT min = arr [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( arr [ i ] < min ) : NEW_LINE INDENT min = arr [ i ] NEW_LINE DEDENT DEDENT return min NEW_LINE DEDENT def getMax ( arr , n ) : NEW_LINE INDENT max = arr [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( arr [ i ] > max ) : NEW_LINE INDENT max = arr [ i ] NEW_LINE DEDENT DEDENT return max NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 4 , 5 , 3 , 2 , 6 ] NEW_LINE n = len ( arr ) NEW_LINE if ( areConsecutive ( arr , n ) == True ) : NEW_LINE INDENT print ( " ▁ Array ▁ elements ▁ are ▁ consecutive ▁ " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " ▁ Array ▁ elements ▁ are ▁ not ▁ consecutive ▁ " ) NEW_LINE DEDENT DEDENT