import sys input = sys.stdin.readline 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]: print(i+1) break _ = 0 else: print(-1)