#include<iostream>
#include<cstring>
#include<vector>

using namespace std;

const int N = 1500005;

int n, m, a[N], cnt[N], ans[N];

int main()
{
	scanf("%d%d", &n, &m);
	for(int i = 1; i <= m; ++i)
	{
		scanf("%d", &a[i]);
		++cnt[a[i]];
	}
	int l = -1;
	while(cnt[++l]);
	ans[l] = true;
	for(int i = m + 1; i <= n; ++i)
	{
		scanf("%d", &a[i]);
		++cnt[a[i]];
		if(--cnt[a[i-m]] == 0) ans[a[i-m]] = true;
	}
	l = -1;
	while(!ans[++l]);
	cout << l << endl;
}

#include <bits/stdc++.h>
using namespace std;
#define IOS ios::sync_with_stdio(false); cin.tie(0);
#define FOR(i,s,n) for(int i = (s); i < (n); i++)
#define REP(i,n) FOR(i,0,n)
#define RREP(i,n) for(int i = (n); i >= 0; i--)
#define ALL(n) (n).begin(), (n).end()
#define RALL(n) (n).rbegin(), (n).rend()
#define ATYN(n) cout << ( (n) ? "Yes":"No") << '\n';
#define CFYN(n) cout << ( (n) ? "YES":"NO") << '\n';
#define OUT(n) cout << (n) << '\n';
using ll = long long;
using ull = unsigned long long;
using pii = pair<int,int>;
using pll = pair<ll,ll>;

int main(void)
{
    IOS
    const int N = 26;
    const vector<int> dx = {0,1,0,-1};
    const vector<int> dy = {-1,0,1,0};
    auto isalpha = [](char c) {
        if (c >= 'a' && c <= 'z') return c - 'a';
        else return -1;
    };
    int h, w;
    cin >> h >> w;
    vector<string> ss(h);
    REP(i,h) cin >> ss[i];
    vector<vector<pii>> warp(N);
    pii s,g;
    REP(y,h) REP(x,w) {
        pii p{y,x};
        if (ss[y][x] == 'S') s = p;
        if (ss[y][x] == 'G') g = p;
        int a = isalpha(ss[y][x]);
        if (a >= 0) warp[a].emplace_back(p);
    }

    vector<pii> bfs;
    vector<vector<int>> step(h,vector<int>(w,-1));
    vector<bool> use(N);
    step[s.first][s.second] = 0;
    bfs.emplace_back(s.first,s.second);
    int ans = -1;
    int now = 1;

    while(!bfs.empty() && ans == -1) {
        vector<pii> tmp;
        swap(bfs,tmp);
        for (auto p:tmp) {
            // cerr << cnt[0] << " " << cnt[1] << " " << cnt[2] << endl;
            REP(i,dx.size()) {
                int y2 = p.first + dy[i];
                int x2 = p.second + dx[i];
                if (y2 < 0 || y2 >= h) continue;
                if (x2 < 0 || x2 >= w) continue;
                if (ss[y2][x2] == '#') continue;
                if (step[y2][x2] >= 0) continue;
                if (y2 == g.first && x2 == g.second) {
                    ans = now;
                }
                step[y2][x2] = now;
                bfs.emplace_back(y2,x2);
            }
            int a = isalpha(ss[p.first][p.second]);
            if (a >= 0 && use[a] == false) {
                for (auto p2:warp[a]) {
                    if (step[p2.first][p2.second] >= 0) continue;
                    step[p2.first][p2.second] = now;
                    bfs.emplace_back(p2.first,p2.second);
                }
                use[a] = true;
            }

        }
        now++;
    }

    if (ans > 0) OUT(ans)
    else OUT(-1)

    return 0;
}