Replace every element with the smallest of the others | Java 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
import java . util . * ; class GFG { static void ReplaceElements ( int [ ] arr , int n ) { if ( n < 2 ) { System . out . println ( " Invalid ▁ Input " ) ; return ; } int firstSmallest = Integer . MAX_VALUE ; int secondSmallest = Integer . MAX_VALUE ; for ( int 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 ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] != firstSmallest ) arr [ i ] = firstSmallest ; else arr [ i ] = secondSmallest ; } for ( int i = 0 ; i < n ; ++ i ) { System . out . print ( arr [ i ] + " , ▁ " ) ; } } public static void main ( String [ ] args ) { int arr [ ] = { 4 , 2 , 1 , 3 } ; int n = arr . length ; ReplaceElements ( arr , n ) ; } }