Norway


Given an of distinct integers, an according to the given of .


 

For example,


Input: 

arr[] = { 1, 2, 3, 4, 5 }
pos[] = { 3, 2, 4, 1, 0 }

Output:

arr[] = { 5, 4, 2, 1, 3 }

i.e. if pos[i] = j, then update arr[j] = arr[i] for every index i.
In other words, update arr[pos[i]] = arr[i] for every index i.

 
Simple solution is to create an auxiliary array of size n and for each element in the input array, we set the corresponding values in the auxiliary array. After filling the auxiliary array, we copy it back to the given array. This can be implemented as follows in C.

 

Download   Run Code

Output:

5 4 2 1 3

 
We can also use a map in place of the auxiliary array as demonstrated below in C++:

 

Download   Run Code

Output:

5 4 2 1 3

 
Both above solutions take extra space. The algorithm can be implemented with O(1) extra space as shown below:

 

Download   Run Code

Output:

5 4 2 1 3

 
1 Star  - rating on - Shuffle an array according to the given order of elements2 Stars  - rating on - Shuffle an array according to the given order of elements3 Stars  - rating on - Shuffle an array according to the given order of elements4 Stars  - rating on - Shuffle an array according to the given order of elements5 Stars  - rating on - Shuffle an array according to the given order of elements (2 votes, average: 5.00 out of 5)

- loading - Shuffle an array according to the given order of elementsLoading…

Thanks for reading.

Please use our online compiler to post code in comments. To contribute, get in touch with us.
Like us? Please spread the word and help us grow. Happy coding 🙂
 



Source link

LEAVE A REPLY

Please enter your comment!
Please enter your name here