Given two arrays, how do you check if one is a cyclic permutation of the other?
For example, given a = [1, 2, 3, 1, 5]
, b = [3, 1, 5, 1, 2]
, and c = [2, 1, 3, 1, 5]
we have that a
and b
are cyclic permutations but c
is not a cyclic permutation of either.
Note: the arrays may have duplicate elements.
The standard trick here is to concatenate one of the arrays with itself, and then try to find the 2nd array in the concatenated array.
For example, 'a' concatenated with itself is:
[1, 2, 3, 1, 5, 1, 2, 3, 1, 5]
Since you do see 'b' in this array starting from the 3rd element then a and b are cyclic permutations.
If A and B are cyclic permutations of each other, A will be found in doubled list BB (as will B in AA).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With