n, m = map(int, input().split())
A = list(map(int, input().split()))
B = list(map(int, input().split()))

i = j = 0
x = 1
for _ in range(n * m):
    if A[i] == B[j]:
        print(x)
        exit()
    x += 1
    i += 1
    j += 1
    if i == n:
        i = 0
    if j == m:
        j = 0
    
print(-1)