Created
April 30, 2016 15:06
-
-
Save cruxrebels/a335004a140e3d357136adaa14989287 to your computer and use it in GitHub Desktop.
Math + Array problem
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*Rearrange a given array so that Arr[i] becomes Arr[Arr[i]] with O(1) extra space. | |
Example: | |
Input : [1, 0] | |
Return : [0, 1] | |
Lets say N = size of the array. Then, following holds true : | |
* All elements in the array are in the range [0, N-1] | |
* N * N does not overflow for a signed integer | |
https://www.interviewbit.com/problems/rearrange-array/ */ | |
void Solution::arrange(vector<int> &A) { | |
auto n = A.size(); | |
for(auto i=0; i<n; ++i) | |
{ | |
A[i] += (A[A[i]]%n)*n; | |
} | |
for(auto i=0; i<n; ++i) | |
{ | |
A[i] /= n; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment