def M():return map(int,input().split()) n,m=M() a=list(M()) b=list(M()) for i in range(n * m): if a[i%n]==b[i%m]:exit(print(i+1)) print(-1)