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