Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if two arrays are cyclic permutations

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.

like image 610
dsg Avatar asked May 24 '11 02:05

dsg


2 Answers

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.

like image 134
Himadri Choudhury Avatar answered Oct 19 '22 07:10

Himadri Choudhury


If A and B are cyclic permutations of each other, A will be found in doubled list BB (as will B in AA).

like image 8
Amadan Avatar answered Oct 19 '22 07:10

Amadan