#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
using P = pair<ll,ll>;
#define rep(i,n) for(int (i)=0;(i)<(n);(i)++)
#define rep2(i,m,n) for(int (i)=(m);(i)<(n);(i)++)
#define ALL(obj) (obj).begin(), (obj).end()
#define rALL(obj) (obj).rbegin(), (obj).rend()
const ll INF = 1LL<<60;//1152921504606846976
const int mod = 1000000007;



int main(){
    ios::sync_with_stdio(false);
    cin.tie(0);
    ll n,m;cin>>n>>m;
    vector<ll> a(n);rep(i,n)cin>>a[i];
    set<ll> st;
    rep(i,n+1)st.insert(i);
    vector<ll> cnt(n,0);
    ll ans = INF;
    rep(i,n){
        st.erase(a[i]);
        cnt[a[i]]++;
        if(i>=m){
            cnt[a[i-m]]--;
            if(cnt[a[i-m]]==0)st.insert(a[i-m]);
        }
        if(i>=m-1){
            ans = min(ans, *st.begin());
        }
    }
    cout<<ans<<endl;
    return 0;
}
#include<bits/stdc++.h>
#define int long long
#define ri register signed
#define rd(x) x=read()
#define pos(x) ((((x)-1)/sz)+1)
using namespace std;
const int N=5e5+5;
const int M=3e7+5;
int mod=998244353;
inline int read(){int x=0,f=1;char ch=getchar();while(ch>'9'||ch<'0'){if(ch=='-')f=-1;ch=getchar();}while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}return x*f;}
inline int ksm(int x,int y=mod-2,int z=mod){int ret=1;while (y){if (y&1) ret=(ret*x)%z;x=(x*x)%z;y>>=1;}return ret;}
int n;
struct Node
{
    int a,c;
}p[N];
bool cmp(Node x,Node y){return x.a<y.a;}
char ch[N];
int num[N];
int a,b,c,ans,ans2,ans1,ans3,ans4;
int laa,lab,posa,posb,lac,lapc;
signed main()
{
    rd(n);n*=2;
    for (int i=1;i<=n;i++) 
    {
        rd(p[i].a);
        scanf("%s",ch);
        if (ch[0]=='R') p[i].c=0;
        if (ch[0]=='G') p[i].c=1;
        if (ch[0]=='B') p[i].c=2;
        num[p[i].c]++;
    }
    sort(p+1,p+n+1,cmp);
    if (num[0]%2==0 && num[1]%2==0) {puts("0");return 0;}
    if (num[0]%2==0) a=1,b=2,c=0;
    if (num[1]%2==0) a=0,b=2,c=1;
    if (num[2]%2==0) a=0,b=1,c=2;
    ans=ans1=ans2=ans3=ans4=1e18;
    laa=lab=-1e16;
    //for (int i=1;i<=n;i++) printf("%lld %lld\n",p[i].a,p[i].c);
    for (int i=1;i<=n;i++)
    {
        if (p[i].c==a) ans=min(ans,p[i].a-lab),laa=p[i].a;
        if (p[i].c==b) ans=min(ans,p[i].a-laa),lab=p[i].a;
    }
    laa=lab=lac=-1e16;
    for (int i=1;i<=n;i++)
    {
        if (p[i].c==c)
        {
            if (p[i].a-laa<ans1) ans1=p[i].a-laa,posa=i;
            lapc=i;lac=p[i].a;
        }
        if (p[i].c==a)
        {
            if (p[i].a-lac<ans1) ans1=p[i].a-lac,posa=i;
            laa=p[i].a;
        }
    }
    laa=lab=lac=-1e16;
    for (int i=1;i<=n;i++)
    {
        if (p[i].c==c)
        {
            if (p[i].a-lab<ans2) ans2=p[i].a-lab,posb=i;
            lapc=i;lac=p[i].a;
        }
        if (p[i].c==b)
        {
            if (p[i].a-lac<ans2) ans2=p[i].a-lac,posb=i;
            lab=p[i].a;
        }
    }
    cout<<min(ans,ans1+ans2)<<endl;
}