#include using namespace std; int n, m, w = 1e9; int a[5000], b[5000]; int main() { cin >> n >> m; for (int i = 0; i < n; i++) cin >> a[i]; for (int i = 0; i < m; i++) cin >> b[i]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { int u = (i + n * j) % m; if (a[i] == b[u]) { w = min(w, i + n * j + 1); break; } } } if (w == 1e9) cout << -1 << endl; else cout << w << endl; }