0%

Rotated Version of Two Arrays

Most Frequent Element in an Array

Problem Description

You are given two arrays. Assume that there are no duplicates in each of arrays.
Determine if two arrays are a rotated version of each other.

Example:

Input: A = [1, 2, 3, 4, 5, 6, 7], B = [4, 5, 6, 7, 1 ,2 ,3]
Output: True
Input: A = [1, 2, 3, 4, 5, 6, 7], B = [1, 3, 5, 7, 9, 2, 4]
Output: False

Solutions

One solution that comes up in my mind is to get an element from the first array, then see if that element can be found in the second array. If yes, we use that element as a start point in both arrays and then use two pointers, one for each array, to go through all elements to see if they are all match.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
bool isRotation(std::vector<int> a, std::vector<int> b){
int idx = -1;

if(a.size() != b.size())
return false;

for(int i = 0; i < b.size(); i++){
if(b[i] == a[0]){
idx = i;
break;
}
}

if(idx == -1)
return false;

for(int i = 0; i < a.size(); i++){
if(a[i] != b[idx])
return false;

if(++idx == b.size())
idx = 0;
}

return true;
}
Pseudo code in Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
def is_rotation(A, B):
if A.length != B.length:
return false

key = A[0];
key_i = -1;
for i from 0 to B.length - 1:
if B[i] == key;
key_i = i
break
if key_i == -1:
return false

for i from 0 to A.length - 1:
j = (key_i + i) % A.length
if A[i] != B[j]:
return false

return true