N,M = map(int,input().split()) A = list(map(int,input().split())) B = list(map(int,input().split())) import sys ans = 10 ** 10 for j in range(M): for i in range(N): k = (j * N + i) % M if A[i] == B[k]: print(j * N + i + 1) exit() print(-1)