-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRearrange_an_array_with_O(1)_extra_space.cpp
More file actions
62 lines (48 loc) · 1.19 KB
/
Rearrange_an_array_with_O(1)_extra_space.cpp
File metadata and controls
62 lines (48 loc) · 1.19 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
58
59
60
61
62
//{ Driver Code Starts
#include<bits/stdc++.h>
using namespace std;
// } Driver Code Ends
class Solution{
public:
// arr: input array
// n: size of array
//Function to rearrange an array so that arr[i] becomes arr[arr[i]]
//with O(1) extra space.
void arrange(long long arr[], int n) {
long long maxRange = n;
for(int i = 0; i < n; i++)
{
arr[i] = arr[i] + (arr[arr[i]] % maxRange) * maxRange;
}
for(int i = 0; i < n; i++)
{
arr[i] /= maxRange;
}
}
};
//{ Driver Code Starts.
int main(){
int t;
//testcases
cin>>t;
while(t--){
int n;
//size of array
cin>>n;
long long A[n];
//adding elements to the array
for(int i=0;i<n;i++){
cin>>A[i];
}
Solution ob;
//calling arrange() function
ob.arrange(A, n);
//printing the elements
for(int i=0;i<n;i++){
cout << A[i]<<" ";
}
cout<<endl;
}
return 0;
}
// } Driver Code Ends