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.