Replace every element with the smallest of the others | Javascript code for the above approach . ; There should be atleast two elements ; If current element is smaller than firstSmallest then update both firstSmallest and secondSmallest ; If arr [ i ] is in between firstSmallest and secondSmallest then update secondSmallest ; Replace every element by smallest of all other elements ; Print the modified array . ; Driver code
function ReplaceElements ( arr , n ) { if ( n < 2 ) { document . write ( " " ) ; return ; } let firstSmallest = Number . MAX_VALUE ; let secondSmallest = Number . MAX_VALUE ; for ( let i = 0 ; i < n ; i ++ ) { if ( arr [ i ] < firstSmallest ) { secondSmallest = firstSmallest ; firstSmallest = arr [ i ] ; } else if ( arr [ i ] < secondSmallest && arr [ i ] != firstSmallest ) secondSmallest = arr [ i ] ; } for ( let i = 0 ; i < n ; i ++ ) { if ( arr [ i ] != firstSmallest ) arr [ i ] = firstSmallest ; else arr [ i ] = secondSmallest ; } for ( let i = 0 ; i < n ; ++ i ) { document . write ( arr [ i ] + " " ) ; } } let arr = [ 4 , 2 , 1 , 3 ] ; let n = arr . length ; ReplaceElements ( arr , n ) ;