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 Code
< ? php function rearrange ( & $ arr , $ n ) { for ( $ i = 0 ; $ i < $ n ; $ i ++ ) $ arr [ $ i ] += ( $ arr [ $ arr [ $ i ] ] % $ n ) * $ n ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) $ arr [ $ i ] = intval ( $ arr [ $ i ] / $ n ) ; } function printArr ( & $ arr , $ n ) { for ( $ i = 0 ; $ i < $ n ; $ i ++ ) echo $ arr [ $ i ] . " ▁ " ; echo " STRNEWLINE " ; } $ arr = array ( 3 , 2 , 0 , 1 ) ; $ n = sizeof ( $ arr ) ; echo " Given ▁ array ▁ is ▁ STRNEWLINE " ; printArr ( $ arr , $ n ) ; rearrange ( $ arr , $ n ) ; echo " Modified ▁ array ▁ is ▁ STRNEWLINE " ; printArr ( $ arr , $ n ) ; ? >