text: k | Function to find k - th missing element ; interating over the array ; check if i - th and ( i + 1 ) - th element are not consecutive ; save their difference ; check for difference and given k ; if found ; Input array ; k - th missing element to be found in the array ; calling function to find missing element
code: < ? php function missingK ( & $ a , $ k , $ n ) { $ difference = 0 ; $ ans = 0 ; $ count = $ k ; $ flag = 0 ; for ( $ i = 0 ; $ i < $ n - 1 ; $ i ++ ) { $ difference = 0 ; if ( ( $ a [ $ i ] + 1 ) != $ a [ $ i + 1 ] ) { $ difference += ( $ a [ $ i + 1 ] - $ a [ $ i ] ) - 1 ; if ( $ difference >= $ count ) { $ ans = $ a [ $ i ] + $ count ; $ flag = 1 ; break ; } else $ count -= $ difference ; } } if ( $ flag ) return $ ans ; else return -1 ; } $ a = array ( 1 , 5 , 11 , 19 ) ; $ k = 11 ; $ n = count ( $ a ) ; $ missing = missingK ( $ a , $ k , $ n ) ; echo $ missing ; ? >