-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRearrangeArray.cpp
More file actions
57 lines (40 loc) · 1.56 KB
/
RearrangeArray.cpp
File metadata and controls
57 lines (40 loc) · 1.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
/*
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
LINK: https://www.interviewbit.com/problems/rearrange-array/
*/
void Solution::arrange(vector<int> &A) {
// Do not write main() function.
// Do not read input, instead use the arguments to the function.
// Do not print the output, instead return values as specified
// Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details
int n = A.size();
for(int i = 0; i< n; i++){
A[i] += A[A[i]]%n*n;
}
for(int i = 0; i< n; i++){
A[i] = (int)A[i]/n;
}
}
/*
If you had extra space to do it, the problem will be very easy.
Store a copy of Arr in B.
And then for every element, do Arr[i] = B[B[i]]
Lets restate what we just said for extra space :
If we could somehow store 2 numbers in every index ( that is, Arr[i] can contain the old value and the new value somehow ), then the problem becomes very easy.
NewValue of Arr[i] = OldValue of Arr[OldValue of Arr[i]]
Now, we will do a slight trick to encode 2 numbers in one index.
This trick assumes that N * N does not overflow.
1) Increase every Array element Arr[i] by (Arr[Arr[i]] % n)*n.
2) Divide every element by N.
Given a number as
A = B + C * N if ( B, C < N )
A % N = B
A / N = C
We use this fact to encode 2 numbers into each element of Arr.
*/