N, M = map(int, input().split()) A = list(map(int, input().split())) B = list(map(int, input().split())) i = 0 while i < N * M: if A[i % N] == B[i % M]: print(i + 1) break i += 1 else: print(-1)