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