Elements to be added so that all elements of a range are present in array | Function to count numbers to be added ; Sort the array ; Check if elements are consecutive or not . If not , update count ; Driver code
function countNum ( arr , n ) { let count = 0 ; arr . sort ( ) ; for ( let i = 0 ; i < n - 1 ; i ++ ) if ( arr [ i ] != arr [ i + 1 ] && arr [ i ] != arr [ i + 1 ] - 1 ) count += arr [ i + 1 ] - arr [ i ] - 1 ; return count ; } let arr = [ 3 , 5 , 8 , 6 ] ; let n = arr . length ; document . write ( countNum ( arr , n ) ) ;