Minimum absolute value of ( K – arr [ i ] ) for all possible values of K over the range [ 0 , N – 1 ] | Function to find the minimum absolute value of ( K - arr [ i ] ) for each possible value of K over the range [ 0 , N - 1 ] | ; Traverse the given array arr [ ] ; Stores the mininimum distance to any array element arr [ i ] ; Check if there is no safe position smaller than i ; Check if the current position is between two safe positions ; Take the minimum of two distances ; Check if the current index is a safe position ; Check if there is no safe position greater than i ; Print the minimum distance ; Driver Code
function minimumDistance ( arr , N ) { let ind = 0 ; let prev = arr [ ind ] ; let s = arr . length ; for ( let i = 0 ; i < N ; i ++ ) { let distance = Number . MAX_SAFE_INTEGER ; if ( i < arr [ 0 ] ) { distance = arr [ 0 ] - i ; } else if ( i >= prev && ind + 1 < s && i <= arr [ ind + 1 ] ) { distance = Math . min ( i - prev , arr [ ind + 1 ] - i ) ; if ( i == arr [ ind + 1 ] ) { distance = 0 ; prev = arr [ ind + 1 ] ; ind ++ ; } } else { distance = i - prev ; } document . write ( distance + " " ) ; } } let N = 5 ; let arr = [ 0 , 4 ] ; minimumDistance ( arr , N ) ;