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 repetition ; 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
< ? php function areConsecutive ( $ arr , $ n ) { if ( $ n < 1 ) return false ; $ min = getMin ( $ arr , $ n ) ; $ max = getMax ( $ arr , $ n ) ; if ( $ max - $ min + 1 == $ n ) { $ i ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) { $ 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 ) { $ min = $ arr [ 0 ] ; for ( $ i = 1 ; $ i < $ n ; $ i ++ ) if ( $ arr [ $ i ] < $ min ) $ min = $ arr [ $ i ] ; return $ min ; } function getMax ( $ arr , $ n ) { $ max = $ arr [ 0 ] ; for ( $ i = 1 ; $ i < $ n ; $ i ++ ) if ( $ arr [ $ i ] > $ max ) $ max = $ arr [ $ i ] ; return $ max ; } $ arr = array ( 1 , 4 , 5 , 3 , 2 , 6 ) ; $ n = count ( $ arr ) ; if ( areConsecutive ( $ arr , $ n ) == true ) echo " ▁ Array ▁ elements ▁ are ▁ consecutive ▁ " ; else echo " ▁ Array ▁ elements ▁ are ▁ not ▁ consecutive ▁ " ; ? >