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 ; Create a temp array to hold visited flag of all elements . Note that , calloc is used here so that all values are initialized as false ; If we see an element again , then return false ; If visited first time , then mark the element as visited ; If all elements occur once , then return true ; if ( max - min + 1 != n ) ; UTILITY FUNCTIONS ; Driver program to test above functions
class AreConsecutive { boolean areConsecutive ( int arr [ ] , int n ) { if ( n < 1 ) return false ; int min = getMin ( arr , n ) ; int max = getMax ( arr , n ) ; if ( max - min + 1 == n ) { boolean visited [ ] = new boolean [ n ] ; int i ; for ( i = 0 ; i < n ; i ++ ) { if ( visited [ arr [ i ] - min ] != false ) return false ; visited [ arr [ i ] - min ] = true ; } return true ; } return false ; } int getMin ( int arr [ ] , int n ) { int min = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) { if ( arr [ i ] < min ) min = arr [ i ] ; } return min ; } int getMax ( int arr [ ] , int n ) { int max = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) { if ( arr [ i ] > max ) max = arr [ i ] ; } return max ; } public static void main ( String [ ] args ) { AreConsecutive consecutive = new AreConsecutive ( ) ; int arr [ ] = { 5 , 4 , 2 , 3 , 1 , 6 } ; int n = arr . length ; if ( consecutive . areConsecutive ( arr , n ) == true ) System . out . println ( " Array ▁ elements ▁ are ▁ consecutive " ) ; else System . out . println ( " Array ▁ elements ▁ are ▁ not ▁ consecutive " ) ; } }