Check if array elements are consecutive | Added Method 3 | 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 repitition ; If we do not see a negative value then all elements are distinct ; if ( max - min + 1 != n ) ; UTILITY FUNCTIONS ; Driver program to test above functions
function areConsecutive ( arr , n ) { if ( n < 1 ) return false ; let min = getMin ( arr , n ) ; let max = getMax ( arr , n ) ; if ( max - min + 1 == n ) { let i ; for ( i = 0 ; i < n ; i ++ ) { let j ; if ( arr [ i ] < 0 ) j = - arr [ i ] - min ; else j = arr [ i ] - min ; if ( arr [ j ] > 0 ) arr [ j ] = - arr [ j ] ; else return false ; } return true ; } return false ; } function getMin ( arr , n ) { let min = arr [ 0 ] ; for ( let i = 1 ; i < n ; i ++ ) { if ( arr [ i ] < min ) min = arr [ i ] ; } return min ; } function getMax ( arr , n ) { let max = arr [ 0 ] ; for ( let i = 1 ; i < n ; i ++ ) { if ( arr [ i ] > max ) max = arr [ i ] ; } return max ; } let arr = [ 5 , 4 , 2 , 3 , 1 , 6 ] ; let n = arr . length ; if ( areConsecutive ( arr , n ) == true ) document . write ( " " ) ; else document . write ( " " ) ;