Skip to content

Commit 7649c02

Browse files
authored
Create Rearrange an array with O(1) extra space.cpp
1 parent c9fb36e commit 7649c02

File tree

1 file changed

+90
-0
lines changed

1 file changed

+90
-0
lines changed
Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
/* Problem Statement -:
2+
Given an array arr[] of size N where every element is in the range from 0 to n-1. Rearrange the given array so that arr[i] becomes arr[arr[i]].
3+
4+
Example 1:
5+
Input:
6+
N = 2
7+
arr[] = {1,0}
8+
Output: 0 1
9+
Explanation:
10+
arr[arr[0]] = arr[1] = 0.
11+
arr[arr[1]] = arr[0] = 1.
12+
13+
Example 2:
14+
Input:
15+
N = 5
16+
arr[] = {4,0,2,1,3}
17+
Output: 3 4 2 0 1
18+
Explanation:
19+
arr[arr[0]] = arr[4] = 3.
20+
arr[arr[1]] = arr[0] = 4.
21+
and so on.
22+
23+
Your Task:
24+
You don't need to read input or print anything. The task is to complete the function arrange() which takes arr and N as input parameters and rearranges the elements in the array in-place.
25+
26+
Expected Time Complexity: O(N)
27+
Expected Auxiliary Space: O(1)
28+
29+
Constraints:
30+
1 <= N <= 107
31+
0 <= Arr[i] < N */
32+
33+
//Solution -:
34+
#include<bits/stdc++.h>
35+
using namespace std;
36+
37+
38+
// } Driver Code Ends
39+
40+
41+
class Solution{
42+
public:
43+
// arr: input array
44+
// n: size of array
45+
//Function to rearrange an array so that arr[i] becomes arr[arr[i]]
46+
//with O(1) extra space.
47+
void arrange(long long arr[], int n) {
48+
// Your code here
49+
long long brr[n];
50+
for(int i=0;i<n;i++){
51+
brr[i]=arr[i];
52+
}
53+
for(int i=0;i<n;i++){
54+
arr[i]=brr[brr[i]];
55+
}
56+
57+
}
58+
};
59+
60+
61+
// { Driver Code Starts.
62+
63+
int main(){
64+
65+
int t;
66+
//testcases
67+
cin>>t;
68+
while(t--){
69+
70+
int n;
71+
//size of array
72+
cin>>n;
73+
long long A[n];
74+
75+
//adding elements to the array
76+
for(int i=0;i<n;i++){
77+
cin>>A[i];
78+
}
79+
Solution ob;
80+
//calling arrange() function
81+
ob.arrange(A, n);
82+
83+
//printing the elements
84+
for(int i=0;i<n;i++){
85+
cout << A[i]<<" ";
86+
}
87+
cout<<endl;
88+
}
89+
return 0;
90+
} // } Driver Code Ends

0 commit comments

Comments
 (0)