n, m = map(int, input().split()) A = list(map(int, input().split())) B = list(map(int, input().split())) for i in range(n * m): if A[i % n] != B[i % m]: continue else: print(i+1) break else: print(-1)