r/csinterviewproblems • u/parlezmoose • Dec 17 '15
[Arrays] Write a function to permute an array A, given another array O containing the new position of each element
Write a function that accepts as input two arrays "A" and "O". The first array contains some unknown values. The second array "O" contains the new positions to which the values in A should be moved. The function should permute A in place according to the new positions specified by O.
Example inputs:
A: [A, B, C, D, E]
O: [2, 1, 0, 4, 3]
Example output:
A === [C, B, A, E, D]
You may assume array O is always "complete", i.e. that it contains each index once.
Follow ups: what is the running time of your solution?
6
Upvotes
3
u/parlezmoose Dec 17 '15
One solution is to sort O using some algorithm like quicksort, and concurrently sort A. This would be an O(nlogn) average time solution. Another solution is to iterate through A. At each iteration i, while O[i] !== i, we swap O[i] and O[O[i]], as well as A[i] and A[O[i]].
This solution is O(n)
1
u/[deleted] Dec 19 '15
Java Implementation, O(n):