Rearrange an array so that arr [ i ] becomes arr [ arr [ i ] ] with O ( 1 ) extra space | The function to rearrange an array in - place so that arr [ i ] becomes arr [ arr [ i ] ] . ; First step : Increase all values by ( arr [ arr [ i ] ] % n ) * n ; Second Step : Divide all values by n ; A utility function to print an array of size n ; Driver program to test above functions
function rearrange ( arr , n ) { for ( let i = 0 ; i < n ; i ++ ) arr [ i ] += ( arr [ arr [ i ] ] % n ) * n ; for ( let i = 0 ; i < n ; i ++ ) arr [ i ] = Math . floor ( arr [ i ] / n ) ; } function printArr ( arr , n ) { for ( let i = 0 ; i < n ; i ++ ) document . write ( arr [ i ] + " " ) ; document . write ( " " ) ; } let arr = [ 3 , 2 , 0 , 1 ] ; let n = arr . length ; document . write ( " " ) ; printArr ( arr , n ) ; rearrange ( arr , n ) ; document . write ( " " ) ; printArr ( arr , n ) ;