Given an array of distinct integers, shuffle it according to the given order of elements.

For example,

Input:
 
nums[] = { 1, 2, 3, 4, 5 }
pos[] = { 3, 2, 4, 1, 0 }
 
Output:
 
nums[] = { 5, 4, 2, 1, 3 }
 
i.e., if pos[i] = j, then update nums[j] = nums[i] for every index i.
In other words, update nums[pos[i]] = nums[i] for every index i.

Practice this problem

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

C


Download  Run Code

Output:

5 4 2 1 3

Java


Download  Run Code

Output:

[5, 4, 2, 1, 3]

Python


Download  Run Code

Output:

[5, 4, 2, 1, 3]

 
We can also use a map replacing the auxiliary array, as demonstrated below in C++, Java, and Python:

C++


Download  Run Code

Output:

5 4 2 1 3

Java


Download  Run Code

Output:

[5, 4, 2, 1, 3]

Python


Download  Run Code

Output:

[5, 4, 2, 1, 3]

The time complexity of both above-discussed methods is O(n). However, both solution requires extra space. The algorithm can be implemented with O(1) extra space, as shown below:

C++


Download  Run Code

Output:

5 4 2 1 3

Java


Download  Run Code

Output:

[5, 4, 2, 1, 3]

Python


Download  Run Code

Output:

[5, 4, 2, 1, 3]