Monday, March 3, 2014

Rearrange an array so that arr[i] becomes arr[arr[i]] with O(1) extra space



Idea is to multiply each array element  with n(no of elements) and get remainder of final array

static void rearrangeArr(int a[]){

int n = a.length;
if(n == 0 || n == 1) return;

for(int i = 0 ; i < n; i++)
{
a[i] = a[i]*n;
}

for(int i = 0; i < n; i++)
{
a[i] = a[i] + a[a[i]/n] /n;
}
for(int i = 0; i < n; i++)
{
a[i] = a[i]%n;
System.out.print(a[i] +" ");
}
}


References:
http://www.geeksforgeeks.org/rearrange-given-array-place/

No comments:

Post a Comment