Elements to be added so that all elements of a range are present in array | Function to count numbers to be added ; Make a hash of elements and store minimum and maximum element ; Traverse all elements from minimum to maximum and count if it is not in the hash ; Drivers code
function countNum ( arr , n ) { let s = new Set ( ) ; let count = 0 , maxm = Number . MIN_VALUE , minm = Number . MAX_VALUE ; for ( let i = 0 ; i < n ; i ++ ) { s . add ( arr [ i ] ) ; if ( arr [ i ] < minm ) minm = arr [ i ] ; if ( arr [ i ] > maxm ) maxm = arr [ i ] ; } for ( let i = minm ; i <= maxm ; i ++ ) if ( ! s . has ( i ) ) count ++ ; return count ; } let arr = [ 3 , 5 , 8 , 6 ] ; let n = arr . length ; document . write ( countNum ( arr , n ) ) ;