6.9 java version - apply permutation - why not just swap

#1

It seems to me there is more simple solution which uses O(1) space and O(n) time - just swap the permutation array (well, in real life I prefer not to use functions which are altering the input objects, but for the sake of space complexity)

Here code in Python

def apply_permutation(array, permutations):
for i in range(len(array)):
swap(array,i,permutations[i])
swap(permutations,i,permutations[i])
return array

def swap(array, i, j):
tmp = array[i]
array[i]=array[j]
array[j]=tmp

out = apply_permutation([‘a’,‘b’,‘c’,‘d’],[2,0,1,3])
print ("permutations are "+str(out))
self.assertEqual(out, [‘b’,‘c’,‘a’,‘d’])

code in python fiddle:

0 Likes

#2

Hey @alex440,

Your approach actually uses more than O(1) space since permutation array is modified during the swap.

0 Likes