N,M = map(int,input().split()) lsA = list(map(int,input().split())) lsB = list(map(int,input().split())) NM = N*M for i in range(NM): if lsA[i%N] == lsB[i%M]: print(i+1) break else: print(-1)