#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <ctime>
#include <cctype>
#include <iostream>
#include <iomanip>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <set>
#include <map>
#include <algorithm>

using namespace std;

typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> pii;
typedef vector <int> vi;

#define sqr(x) ((x)*(x))
#define forn(i, n) for (i = 0; i < (int)(n); ++i)
#define pb push_back
#define mp make_pair
#define updMin(a, b) ((a) = min((a), (b)))
#define updMax(a, b) ((a) = max((a), (b)))

const int maxn = 100000 + 100;

int w[maxn];
bool vis[maxn];
vector <vi> g;

ll d[maxn][2];

void dfs(int v)
{
    vis[v] = true;
    int s = g[v].size(), i, to;
    ll a, b;
    a = b = 0;
    forn(i, s) {
        to = g[v][i];
        if (vis[to])
            continue;
        dfs(to);
        updMax(a, d[to][0]);
        updMax(b, d[to][1]);
    }
    ll c = w[v];
    c += a - b;
    if (c > 0) {
        b += c;
    } else {
        a += -c;
    }
    d[v][0] = a;
    d[v][1] = b;
}

int main()
{
#ifndef ONLINE_JUDGE
    freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout);
#endif

    int n, i, j, a, b;
    scanf("%d", &n);
    g.resize(n);
    forn(i, n - 1) {
        scanf("%d%d", &a, &b);
        --a;
        --b;
        g[a].pb(b);
        g[b].pb(a);
    }
    forn(i, n)
        scanf("%d", &w[i]);
    dfs(0);
    ll ans = d[0][0] + d[0][1];
    printf("%I64d\n", ans);
    return 0;
}


#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>

using namespace std;

int n;
vector<int> a[1<<17];
long long ndec[1<<17], ninc[1<<17];
int val[1<<17];

long long dfs()
{
	int i, j;
	static int x[1<<17], iy[1<<17];
	memset(iy, -1, sizeof(iy));
	x[0] = 0;
	for ( i = 0; i >= 0; )
	{
		int xx = x[i];
		if ( ++iy[i] < a[xx].size() )
		{
			int yy = a[xx][iy[i]];
			if ( i > 0 && x[i-1] == yy )
				continue;
			x[++i] = yy;
			continue;
		}
		else
		{
			long long t;
			for ( j = 0; j < a[xx].size(); ++j )
			{
				int yy = a[xx][j];
				if ( ndec[xx] < (t = ndec[yy]) )
					ndec[xx] = ndec[yy];
				if ( ninc[xx] < (t = ninc[yy]) )
					ninc[xx] = ninc[yy];
			}
			t = val[xx] + ninc[xx] - ndec[xx];
			if ( t < 0 )
				ninc[xx] += -t;
			else
				ndec[xx] += t;
			iy[i--] = -1;
		}
	}
	return ndec[0] + ninc[0];
}

int main()
{
	int i;
	scanf("%d", &n);
	for ( i = 0; ++i < n; )
	{
		int x, y;
		scanf("%d%d", &x, &y);
		--x;
		--y;
		a[x].push_back(y);
		a[y].push_back(x);
	}
	for ( i = 0; i < n; ++i )
		scanf("%d", val+i);
	printf("%I64d\n", dfs());
	return 0;
}


#include <iostream>
#include <vector>
using namespace std;

#pragma comment (linker, "/STACK:16000000");

int n;
vector<int> g[100005];
long long v[100005];
pair<long long, long long> ans;

pair<long long, long long> calc(int num, int p = -1) {
	pair<long long, long long> res = make_pair(0LL, 0LL);
	pair<long long, long long> temp;

	for (int i = 0; i < g[num].size(); i++) {
		int to = g[num][i];

		if (to == p) continue;
		temp = calc(to, num);
		res.first = max(res.first, temp.first);
		res.second = max(res.second, temp.second);
	}
	res.first += max(0LL, v[num]);
	res.second += max(0LL, -v[num]);

	return res;
}

int main() {

#ifndef ONLINE_JUDGE
	freopen("input.txt", "rt", stdin);
	freopen("output.txt", "wt", stdout);
#endif

	cin >> n;
	for (int i = 0; i < n - 1; i++) {
		int a, b;

		cin >> a >> b;
		g[a].push_back(b);
		g[b].push_back(a);
	}
	for (int i = 1; i <= n; i++) {
		cin >> v[i];
	}
	ans = calc(1);
	cout << ans.first + ans.second;

	return 0;
}


#include <iostream>
#include <vector>
using namespace std;

#pragma comment (linker, "/STACK:16000000");

int n;
vector<int> g[100005];
long long v[100005];
pair<long long, long long> ans;

pair<long long, long long> calc(int num, int p = -1) {
	pair<long long, long long> res = make_pair(0LL, 0LL);
	pair<long long, long long> temp;
	long long delta;

	for (int i = 0; i < g[num].size(); i++) {
		int to = g[num][i];

		if (to == p) continue;
		temp = calc(to, num);
		res.first = max(res.first, temp.first);
		res.second = max(res.second, temp.second);
	}
	delta = v[num] - res.first + res.second;
	res.first += max(0LL, delta);
	res.second += max(0LL, -delta);

	return res;
}

int main() {

#ifndef ONLINE_JUDGE
	freopen("input.txt", "rt", stdin);
	freopen("output.txt", "wt", stdout);
#endif

	cin >> n;
	for (int i = 0; i < n - 1; i++) {
		int a, b;

		cin >> a >> b;
		g[a].push_back(b);
		g[b].push_back(a);
	}
	for (int i = 1; i <= n; i++) {
		cin >> v[i];
	}
	ans = calc(1);
	cout << ans.first + ans.second;

	return 0;
}


#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <map>
#include <algorithm>
#include <ctime>
#include <iomanip>
#include <iterator>
#include <set>
#include <string>
#include <stack>
#include <cmath>
#include <stdio.h>
#include <cstring>

#define ii <int , int>

#define mp make_pair
#define all(v) v.begin(),v.end()
#define loop(i, n) for (int i = 0; i < n; i++)
#define pb push_back
#define sz(v) (int)v.size()
#define X first
#define Y second

#define Pi(x) printf("%d ", (x))
#define Pii(x, y) printf("%d %d ", (x), (y))
#define Piii(x, y, z) printf("%d %d %d", (x), (y), (z))
#define Pl(x) printf("%I64d ", (x))
#define Pll(x, y) printf("%I64d I64d ", (x), (y))
#define Plll(x, y, z) printf("%I64d I64d I64d ", (x), (y), (z))
#define Ps(x) printf("%s", (x))
#define Pe() printf("\n")
#define Pe1(i) for (int j = 0; j < i; j++) printf(" ")

#define Si(x) scanf("%d",&x)
#define Sii(x, y) scanf("%d %d", (&x), (&y))
#define Siii(x, y, z) scanf("%d %d %d", (&x), (&y), (&z))
#define Sl(x) scanf("%I64d", (&x))
#define Sll(x, y) scanf("%I64d %I64d", (&x), (&y))
#define Slll(x, y, z) scanf("%I64d %I64d %I64d", (&x), (&y), (&z))
#define Ss(x) scanf("%s", (&x))

using namespace std;

typedef long long ll;
typedef vector<int > vi;
typedef vector<vi> vvi;
typedef pair ii pii;
typedef vector <pii> vii;
typedef map ii mii;
typedef set <int > si;
typedef multiset <int > msi;
typedef multimap <int , int> mmi;
typedef vector <ll> vl;
typedef pair<ll, ll> pll;
typedef vector <pll> vll;

const ll nInf = -1000000000;
const ll pInf = 1000000000;
const ll mod     = 1000000007;
const int MAXN = 1e5 + 10;

int n, num[MAXN];
vi g[MAXN];
int inc[MAXN], dec1[MAXN];

void getdata();
void preproc();
void solve();
void dfs(int v, int p);

int main()
{
        //freopen( "input.txt", "r" , stdin);
       // freopen( "output.txt", "w" , stdout);
        int t = 1;
       // scanf("%d", &t);
        for (int i = 0;i < t; i++)
        {
               getdata();
               preproc();
               solve();
        }
        return 0;
}

void getdata()
{
	scanf("%d", &n);
	int a, b;
	for (int i = 1; i < n; i++)
	{
		scanf("%d %d", &a, &b);
		a--;b--;
		g[a].pb(b);
		g[b].pb(a);
	}
	for (int i = 0;i < n ;i++)
	{
		scanf("%d", &num[i]);
	}
}

void preproc()
{

}

void solve()
{
	dfs(0, -1);
	printf("%d\n", inc[0] + dec1[0]);
/*	for (int i = 0;i < n; i++)
	{
		printf("%d %d\n", inc[i], dec1[i]);
	}*/
}

void dfs(int v, int p)
{
/*	if (num[v] > 0)
	{
		dec1[v] = num[v];
	}
	else
	{
		inc[v] = abs(num[v]);
	}*/
	int maxinc = 0;//inc[v];
	int maxdec = 0;//dec1[v];
	for (int i = 0;i < sz(g[v]); i++)
	{
		int to = g[v][i];
		if (to == p) continue;
		dfs(to, v);
		maxinc = max(maxinc, inc[to]);
		maxdec = max(maxdec, dec1[to]);
	}
	inc[v] = maxinc;
	dec1[v] = maxdec;
	if (num[v] + inc[v] - dec1[v] > 0) dec1[v] += num[v] + inc[v] - dec1[v];
	else inc[v] += abs(num[v] + inc[v] - dec1[v]);
}


#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <map>
#include <algorithm>
#include <ctime>
#include <iomanip>
#include <iterator>
#include <set>
#include <string>
#include <stack>
#include <cmath>
#include <stdio.h>
#include <cstring>

#define ii <int , int>

#define mp make_pair
#define all(v) v.begin(),v.end()
#define loop(i, n) for (int i = 0; i < n; i++)
#define pb push_back
#define sz(v) (int)v.size()
#define X first
#define Y second

#define Pi(x) printf("%d ", (x))
#define Pii(x, y) printf("%d %d ", (x), (y))
#define Piii(x, y, z) printf("%d %d %d", (x), (y), (z))
#define Pl(x) printf("%I64d ", (x))
#define Pll(x, y) printf("%I64d I64d ", (x), (y))
#define Plll(x, y, z) printf("%I64d I64d I64d ", (x), (y), (z))
#define Ps(x) printf("%s", (x))
#define Pe() printf("\n")
#define Pe1(i) for (int j = 0; j < i; j++) printf(" ")

#define Si(x) scanf("%d",&x)
#define Sii(x, y) scanf("%d %d", (&x), (&y))
#define Siii(x, y, z) scanf("%d %d %d", (&x), (&y), (&z))
#define Sl(x) scanf("%I64d", (&x))
#define Sll(x, y) scanf("%I64d %I64d", (&x), (&y))
#define Slll(x, y, z) scanf("%I64d %I64d %I64d", (&x), (&y), (&z))
#define Ss(x) scanf("%s", (&x))

using namespace std;

typedef long long ll;
typedef vector<int > vi;
typedef vector<vi> vvi;
typedef pair ii pii;
typedef vector <pii> vii;
typedef map ii mii;
typedef set <int > si;
typedef multiset <int > msi;
typedef multimap <int , int> mmi;
typedef vector <ll> vl;
typedef pair<ll, ll> pll;
typedef vector <pll> vll;

const ll nInf = -1000000000;
const ll pInf = 1000000000;
const ll mod     = 1000000007;
const int MAXN = 1e5 + 10;

int n, num[MAXN];
vi g[MAXN];
ll inc[MAXN], dec1[MAXN];

void getdata();
void preproc();
void solve();
void dfs(int v, int p);

int main()
{
        //freopen( "input.txt", "r" , stdin);
       // freopen( "output.txt", "w" , stdout);
        int t = 1;
       // scanf("%d", &t);
        for (int i = 0;i < t; i++)
        {
               getdata();
               preproc();
               solve();
        }
        return 0;
}

void getdata()
{
	scanf("%d", &n);
	int a, b;
	for (int i = 1; i < n; i++)
	{
		scanf("%d %d", &a, &b);
		a--;b--;
		g[a].pb(b);
		g[b].pb(a);
	}
	for (int i = 0;i < n ;i++)
	{
		scanf("%d", &num[i]);
	}
}

void preproc()
{

}

void solve()
{
	dfs(0, -1);
	//printf("%d\n", inc[0] + dec1[0]);
	cout << inc[0] + dec1[0] << endl;
/*	for (int i = 0;i < n; i++)
	{
		printf("%d %d\n", inc[i], dec1[i]);
	}*/
}

void dfs(int v, int p)
{
/*	if (num[v] > 0)
	{
		dec1[v] = num[v];
	}
	else
	{
		inc[v] = abs(num[v]);
	}*/
	ll maxinc = 0;//inc[v];
	ll maxdec = 0;//dec1[v];
	for (int i = 0;i < sz(g[v]); i++)
	{
		int to = g[v][i];
		if (to == p) continue;
		dfs(to, v);
		maxinc = max(maxinc, inc[to]);
		maxdec = max(maxdec, dec1[to]);
	}
	inc[v] = maxinc;
	dec1[v] = maxdec;
	if (num[v] + inc[v] - dec1[v] > 0) dec1[v] += num[v] + inc[v] - dec1[v];
	else inc[v] += abs(num[v] + inc[v] - dec1[v]);
}


#include <cstdio>
#include <cstdlib>
#include <sstream>
#include <iostream>
#include <cmath>
#include <cstring>
#include <algorithm>
#include <string>
#include <utility>
#include <vector>
#include <queue>
#include <map>
#include <set>
using namespace std;
#define pai acos(-1)
#define ll long long

vector<int> f[100010];
int p[100010];
struct node
{
    ll x,y;
};

node dfs(int x,int fu)
{
    node ans;
    ans.x=ans.y=0;
    int flag = 0;
    for(int i=0;i<f[x].size();i++)
    {
        int v = f[x][i];
        if(v == fu) continue;
        node tmp = dfs(v, x);
        flag  = 1;
        ans.x = max(ans.x, tmp.x);
        ans.y = min(ans.y, tmp.y);
    }

    if(flag == 0)
    {
        if(p[x] < 0){
            ans.x = 0-p[x];
            ans.y = 0;
        } else
        {
            ans.x = 0;
            ans.y = 0-p[x];
        }
        return ans;
    }
    else
    {
        ll he = p[x]+ans.x+ans.y;
        if(he<0)
        {
            ans.x-=he;
        } else
            ans.y-=he;
        return ans;
    }
}
int main()
{
    int n;
    cin>>n;
    for(int i=1;i<n;i++)
    {
        int a,b;
        cin>>a>>b;
        f[a].push_back(b);
        f[b].push_back(a);
    }
    for(int i=1;i<=n;i++)
        cin>>p[i];
    node ans = dfs(1,-1);
    cout<<abs(ans.x)+abs(ans.y)<<endl;
}


#include<stdio.h>
#include<string.h>
#include<math.h>
#include<vector>
using namespace std;

#define maxm 100100
#define ii __int64

struct node{
    ii plus,minus;
    node(){}
    node(ii a,ii b){plus=a; minus=b;}
};

vector<int>v[maxm];
int val[maxm],n;

ii maxi(ii a,ii b){
    if(a>b) return a; return b;
}
node cal(int s,int pre);

int main(){

    int i,j,k,l,test,t=1;

    //freopen("in.txt","r",stdin);

    scanf("%d",&n);

    for(i=1;i<n;i++){
        scanf("%d %d",&k,&l);
        v[k].push_back(l);
        v[l].push_back(k);
    }

    for(i=1;i<=n;i++){
        scanf("%d",&val[i]);
    }

    node ans=cal(1,1);
    printf("%I64d\n",ans.plus+ans.minus);

    return 0;
}

node cal(int s,int pre){

    int i,j,k,l;
    node ret=node(0,0),ret1;
    ii pl=0,pm=0;

    for(i=0;i<v[s].size();i++){
        k=v[s][i];
        if(k==pre) continue;
        ret1=cal(k,s);
        pl=maxi(pl,ret1.plus);
        pm=maxi(pm,ret1.minus);
    }
    ii vv=pl-pm;
    vv=val[s]-vv;
    if(vv>=0) ret.plus=vv;
    else ret.minus=-vv;

    ret.plus+=pl; ret.minus+=pm;
    return ret;
}


										/* in the name of Allah */
#include <iostream>
#include <memory.h>
#include <algorithm>
#include <sstream>
#include <cmath>
#include <cstdio>
#include <string>
#include <vector>
#include <queue>
#include <map>

using namespace std;

#define int64 long long
#define P pair<int64, int64>

int n;
vector <int> adj[100010];
int64 v[100010];

P dfs(int idx, int par){
	int64 mn = 0, mx = 0;
	for(int i = 0; i < adj[idx].size(); i++){
		int j = adj[idx][i];
		if(j == par) continue;
		P tmp = dfs(j, idx);
		mn = max(mn, tmp.first);
		mx = max(mx, tmp.second);
	}
	int64 d = v[idx] + mx - mn;
	if(d < 0)
		mx += -d;
	else mn += d;
	return P(mn, mx);
}

int main(){
	cin >> n;
	int a, b;
	for(int i = 1; i < n; i++){
		cin >> a >> b;
		a--, b--;
		adj[a].push_back(b);
		adj[b].push_back(a);
	}
	for(int i = 0; i < n; i++)
		cin >> v[i];
	P res = dfs(0, -1);
	cout << res.first + res.second << endl;
	return 0;
}


										/* in the name of Allah */
#include <iostream>
#include <memory.h>
#include <algorithm>
#include <sstream>
#include <cmath>
#include <cstdio>
#include <string>
#include <vector>
#include <queue>
#include <map>

using namespace std;

#define int64 long long
#define P pair<int64, int64>

int n;
vector <int> adj[100010];
int64 v[100010];

P dfs(int idx, int par){
	int64 mn = 0, mx = 0;
	for(int i = 0; i < adj[idx].size(); i++){
		int j = adj[idx][i];
		if(j == par) continue;
		P tmp = dfs(j, idx);
		mn = max(mn, tmp.first);
		mx = max(mx, tmp.second);
	}
	int64 d = v[idx] + mx - mn;
	if(d < 0)
		mx += -d;
	else mn += d;
	return P(mn, mx);
}

int main(){
	cin >> n;
	int a, b;
	for(int i = 1; i < n; i++){
		cin >> a >> b;
		a--, b--;
		adj[a].push_back(b);
		adj[b].push_back(a);
	}
	for(int i = 0; i < n; i++)
		cin >> v[i];
	P res = dfs(a, -1);
	cout << res.first + res.second << endl;
	return 0;
}


#include <vector>
#include <list>
#include <map>
#include <set>
#include <queue>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <fstream>

using namespace std;

#define JUDGE "IO.txt"
#define GBIT(X, i) (x&(i<<i))
#define MSET(X, i) (memeset(X, i, sizeof(X));)
#define BETWEEN(X, A, B) ((X>=A && X<=B))

typedef pair<long long, long long> LL;

const int MAX = 100001;
bool vis[MAX];
long long cst[MAX];
vector<long long> adj[MAX];

int c = 0;
LL dfs(int node, int crnt)
{
    if(vis[node])
        return make_pair(0,0);
    else
    {
        long long pos = 0, neg = 0, ss = cst[node];
        LL leaf;
        vis[node] = true;
        for(int i =0;i < adj[node].size(); ++i)
        {
            LL ret = dfs(adj[node][i], crnt);
            ss += ret.first;
            ss += ret.second;
            neg = min(neg, ret.first);
            pos = max(pos, ret.second);
        }

        leaf.first = neg;
        leaf.second = pos;
        if(ss > 0)
            leaf.first -= ss;
        else if(ss < 0)
            leaf.second += abs(ss);

        return leaf;
    }
}

int main() {

    ifstream fin (JUDGE);

    int n, a, b;
    cin>>n;

    for(int i = 1; i < n; i++)
    {
        cin>>a>>b; --a, --b;
        adj[a].push_back(b);
        adj[b].push_back(a);
    }

    for(int i = 0; i < n; ++i)
        cin>>cst[i];

    LL gt = dfs(0, INT_MAX);

    cout<<abs(gt.first) + gt.second;
}
// END KAWIGIEDIT TESTING


def findLen(s):
    minLen = float("inf")

    def findForCurr(currStart, s):
        nonlocal minLen
        seen = set()
        i = currStart
        while len(seen)<3 and i<len(s):
            if s[i] not in seen:
                seen.add(s[i])
            i += 1
        # print(seen, currStart, i)
        if len(seen)==3:
            minLen = min(minLen, i-currStart)

    lastStart = '#'
    i = 0
    while i<len(s):
        if s[i] != lastStart:
            findForCurr(i, s)
        i += 1
    if minLen==float("inf"): return 0
    return minLen

t = int(input())
for i in range(t):
    s = input()
    print(findLen(s))


from collections import defaultdict

def findLen(s):
    N = len(s)
    def checkFor(size):
        left, right = 0, size-1
        c = defaultdict(int)
        for i in range(left, right+1):
            c[s[i]] += 1

        while right < N-1:
            if c["1"]>0 and c["2"]>0 and c["3"]>0: return True
            c[s[left]] -= 1
            left += 1
            right += 1
            c[s[right]] += 1

        if c["1"]>0 and c["2"]>0 and c["3"]>0: return True
        else: return False

    left, right = 0, N
    while left < right:
        mid = (left+right)//2
        if checkFor(mid):
            right = mid
        else:
            left = mid + 1

    if left <N or left==N and checkFor(N): return left

    else: return 0

t = int(input())
for i in range(t):
    s = input()
    print(findLen(s))


def findLen(s):
    minLen = float("inf")

    def findForCurr(currStart, s):
        nonlocal minLen
        seen = set()
        i = currStart
        while len(seen)<3 and i<len(s):
            if s[i] not in seen:
                seen.add(s[i])
            i += 1
        # print(seen, currStart, i)
        if len(seen)==3:
            minLen = min(minLen, i-currStart)

    i = 0
    while i<len(s)-3:
        if s[i] != s[i+1]:
            findForCurr(i, s)
        i += 1
    if minLen==float("inf"): return 0
    return minLen

t = int(input())
for i in range(t):
    s = input()
    print(findLen(s))


from collections import deque

def check(arr):
    if '1' in arr and '2' in arr and '3' in arr:
        return True
    return False

def solution():
    n = input()

    s = 0
    e = 0

    d = deque([])
    ans = 100000000
    while 1:

        if ans == 3:
            break
        if check(d):
            ans = min(len(d), ans)
            d.popleft()
            s += 1
        elif e < len(n):
            d.append(n[e])
            e += 1
        elif s == len(n) - 1:
            break
        else:
            s += 1
            d.popleft()

    if ans == 100000000:
        print(0)
    else:
        print(ans)

for _ in range(int(input())):
    solution()


from collections import deque

def check(dic):
    if dic['1'] > 0 and dic['2'] and dic['3']:
        return True
    return False

def solution():
    n = input()

    s = 0
    e = 0

    d = deque([])
    d_dic = {'1': 0, '2': 0, '3': 0}
    ans = 100000000
    while 1:
        if ans == 3:
            break
        if check(d_dic):
            ans = min(len(d), ans)
            r = d.popleft()
            d_dic[r] -= 1
            s += 1
        elif e < len(n):
            v = n[e]
            d.append(v)
            if v in d_dic:
                d_dic[v] += 1
            else:
                d_dic[v] = 1
            e += 1
        elif s == len(n) - 1:
            break
        else:
            s += 1
            r = d.popleft()
            d_dic[r] -= 1

    if ans == 100000000:
        print(0)
    else:
        print(ans)

for _ in range(int(input())):
    solution()


def check(arr):
    if '1' in arr and '2' in arr and '3' in arr:
        return True
    return False

def solution():
    n = input()

    s = 0
    e = 0

    d = []
    ans = 100000000
    while 1:

        if ans == 3:
            break
        if check(d):
            ans = min(len(d), ans)
            d.pop(0)
            s += 1
        elif e < len(n):
            d.append(n[e])
            e += 1
        elif s == len(n) - 1:
            break
        else:
            s += 1
            d.pop(0)

    if ans == 100000000:
        print(0)
    else:
        print(ans)

for _ in range(int(input())):
    solution()


#coding isn't(not) for me. i have seen this solution before

t=int(input())
while t:
	s=input()
	if s.count('1')==0 or s.count('2')==0 or s.count('3')==0:
		print("0")
		t-=1
		continue
	cl=[]
	sv=s[0]
	counter=1
	for i in range(1,len(s)):
		if s[i]==sv:
			counter+=1
		else:
			cl.append((sv,counter))
			counter=1
			sv=s[i]
	cl.append((sv,counter))
	ans=len(s)
	for i in range(0,len(cl)-2):
		if cl[i][0]!=cl[i+1][0] and cl[i+1][0]!=cl[i+2][0] and cl[i+2][0]!=cl[i][0]:
			ans=min(ans,cl[i+1][1]+2)
	print(ans)
	t-=1
	#unknown_2433


t=int(input())
while t:
	s=input()
	se=set(s)
	if len(se)==3:
		ans=[]
		for i in range(0,len(s)-2):
			k=i-1
			temp=-1
			a=0
			b=0
			c=0
			z=0
			while a==0 or b==0 or c==0:
				k+=1
				temp=k-i+1
				if k<len(s):
					if s[k]=='1':
						a+=1
					elif s[k]=='2':
						b+=1
					else:
						c+=1
				else:
					z=1
					break
			if z==0:
				ans.append(temp)
				if min(ans)==3:
					break
			else:
				break
		print(min(ans))

	else:
		print("0")
	t-=1


#coding isn't(not) for me. i have seen this solution before

t=int(input())
while t:
	s=input()
	if s.count('1')==0 or s.count('2')==0 or s.count('3')==0:
		print("0")
		continue
	cl=[]
	sv=s[0]
	counter=1
	for i in range(1,len(s)):
		if s[i]==sv:
			counter+=1
		else:
			cl.append((sv,counter))
			counter=1
			sv=s[i]
	cl.append((sv,counter))
	ans=len(s)
	for i in range(0,len(cl)-2):
		if cl[i][0]!=cl[i+1][0] and cl[i+1][0]!=cl[i+2][0] and cl[i+2][0]!=cl[i][0]:
			ans=min(ans,cl[i+1][1]+2)
	print(ans)
	t-=1
	#unknown_2433


t=int(input())
while t:
	s=input()
	se=set(s)
	if len(se)==3:
		ans=len(s)
		for i in range(0,len(s)-2):
			k=i-1
			temp=-1
			a=0
			b=0
			c=0
			z=0
			while a==0 or b==0 or c==0:
				k+=1
				temp=k-i+1
				if k<len(s):
					if s[k]=='1':
						a+=1
					elif s[k]=='2':
						b+=1
					else:
						c+=1
				else:
					z=1
					break
			if z==0:
				if ans<temp:
					continue
				else:
					ans=temp
					if ans==3:
						break
			else:
				break
		print(ans)

	else:
		print("0")
	t-=1


t=int(input())
while t:
	s=input()
	ans=len(s)
	for i in range(0,len(s)-2):
		k=i-1
		temp=-1
		a=0
		b=0
		c=0
		z=0
		while a==0 or b==0 or c==0:
			k+=1
			if k<len(s):
				if s[k]=='1':
					a+=1
				elif s[k]=='2':
					b+=1
				else:
					c+=1
			else:
				z=1
				break
		temp=k-i+1
		if z==0:
			if ans>temp:
				ans=temp
				if ans==3:
					break
		else:
			if ans==len(s):
				ans=0
				break
	print(ans)
	t-=1


#include<bits/stdc++.h>
using namespace std;

int main(){
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);

	int t;
	cin >> t;
	while(t--){
		string s;
		cin >> s;
		int i, j;
		vector<int> v = {0, 0, 0};
		vector<int> ans;

		int ind1=0, ind2=0, flag = 0;
		v[s[0]-'1']++;

		while(ind1 != s.size()){
			if(v[s[ind2]-'1'] > 1){
				v[s[ind2]-'1']--;
				ind2++;
				continue;
			}

			if(v[0] != 0 && v[1] != 0 && v[2] != 0){
				ans.push_back(ind1-ind2+1);
				v[s[ind2]-'1']--;
				ind2++;
				continue;
			}
			ind1++;
			v[s[ind1]-'1']++;

			// for(auto x: v)
			// 	cout << x << ' ';
			// cout << "\n";
		}

		if(ans.size() == 0)
			cout << "0\n";
		else
			cout << *min_element(ans.begin(), ans.end()) << "\n";
	}
}


def find(arr, ind):
	s = 0
	e = len(arr)-1
	ans = -1
	while s <= e:
		# print(s, e)
		mid = (s+e)//2
		if arr[mid] > ind:
			ans = arr[mid]
			e = mid-1
		else:
			s = mid+1
	return ans

t = int(input())
for _ in range(t):
	s = input()
	a, b, c = [], [], []

	for i in range(len(s)):
		if s[i] == '1':
			a += [i]
		elif s[i] == '2':
			b += [i]
		else:
			c += [i]

	ans = 9999999999
	# print(a, b, c)
	for i in range(len(s)):
		if s[i] == '1':
			x = find(b, i)
			y = find(c, i)
		if s[i] == '2':
			x = find(a, i)
			y = find(c, i)
		if s[i] == '3':
			x = find(a, i)
			y = find(b, i)

		# print(i, x, y, max(x, y), max(x, y)-i+1)

		if x == -1 or y == -1:
			continue

		ans = min(ans, max(x, y)-i+1)

	if ans == 9999999999:
		print(0)
	else:
		print(ans)


t = int(input())
for _ in range(t):
    s = input()
    o = -1
    tw = -1
    th = -1
    b = 2000000
    for i in range(len(s)):
        if s[i]=="1":
            o = i
        elif s[i]=="2":
            tw = i
        else:
            th = i

        if o!= -1 and tw!= -1 and th != -1:
            z = max([o,th,tw]) - min([o,th,tw]) + 1
            if b > z:
                b = z
    if b == 2000000:
        print(0)
    else:
        print(b)


for _ in range(int(input())):
    s=input()
    if len(set(s))<3:print(0)
    else:
        f=False
        for i in range(3,len(s)+1):
            for j in range(len(s)+1-i):
                #print(s[j:j+i])
                if len(set(s[j:j+i]))==3:
                    print(i)
                    f=True
                if f==True:break
            if f == True: break


for _ in range(int(input())):
    s=input()
    if len(set(s))<3:
        print(0)
    else:
        ans=len(s)
        mark=[0,0,0]
        mark[0]=s.find('1')
        mark[1]=s.find('2')
        mark[2]=s.find('3')
        r=max(mark)     #找到有1 2 3 的第一个串，确定右边的位置
        l=-1
        while ans>3 and r!=-1:
            if mark[0]!=r:mark[0]=s.rfind('1',l+1,r)
            if mark[1] != r: mark[1] = s.rfind('2', l+1,r)
            if mark[2] != r: mark[2] = s.rfind('3', l+1,r)   #这里是确定每一串含有 1 2 3的子串中最短的，从右边往左边找
            if -1 in mark:break
            l=min(mark)
            ans=min(ans,r+1-l)
            r=s.find(s[l],r)
            mark[int(s[l])-1]=r  #将上次截取的最小位置值清空，循环找下一个次数的位置
        print(ans)


for _ in range(int(input())):
    s=input()
    if len(set(s))<3:print(0)
    else:
        f=False
        for i in range(3,len(s)+1):
            for j in range(len(s)+1-i):
                #print(s[j:j+i])
                if len(set(s[j:j+i]))==3 or s[len(s)-i-j:len(s)-i-j+i]==3:
                    print(i)
                    f=True
                if f==True:break
            if f == True: break


for _ in range(int(input())):
    s=input()
    if len(set(s))<3:
        print(0)
        continue
    else:
        l=0
        ans=len(s)
        for i in range(l+2,len(s)):
            if len(set(s[l:i+1]))==3:
                r=i
                break
        for i in range(r-2,-1,-1):
            if len(set(s[i:r+1]))==3:
                l=i
                break
        while l<=len(s)-3 and ans!=3 and r!=-1:
            ans=min(ans,r-l+1)
            r=s.find(s[l],l+1)
            for i in range(r - 2, -1, -1):
                if len(set(s[i:r + 1])) == 3:
                    l = i
                    break
        print(ans)


for _ in range(int(input())):
    s=input()
    if len(set(s))<3:
        print(0)
    else:
        ans=len(s)
        mark=[0,0,0]
        mark[0]=s.find('1')
        mark[1]=s.find('2')
        mark[2]=s.find('3')
        r=max(mark)
        l=-1
        while ans>3 and r!=-1:
            if mark[0]!=r:mark[0]=s.rfind('1',l+1,r)
            if mark[1] != r: mark[1] = s.rfind('2', l+1,r)
            if mark[2] != r: mark[2] = s.rfind('3', l+1,r)
            if -1 in mark:break
            l=min(mark)
            ans=min(ans,r+1-l)
            r=s.find(s[l],r)
            mark[int(s[l])-1]=r
        print(ans)


for _ in range(int(input())):
    s=input()
    if len(set(s))<3:print(0)
    else:
        l=0
        for i in range(2,len(s)):
            if len(set(s[l:i+1]))==3:
                r=i
                break
        for i in range(r-2,-1,-1):
            if len(set(s[i:r+1]))==3:
                l=i
                break
        print(r-l+1)


for _ in range(int(input())):
    s=input()
    n=len(s)
    minn=200001
    l=[0,0,0,0]
    for i in range(n):
        k=int(s[i])
        l=[0,0,0,0]
        l[k]=1
        g,count=0,1
        for j in range(i+1,n):
            k=int(s[j])
            if l[k]==0:
                l[k]=1
                g+=1
            count+=1
            if g==2:
                break
        if g==2:
            minn=min(minn,count)
        if g<2 or minn==3:
            break
    if minn==200001:
        print(0)
    else:
        print(minn)


for _ in range(int(input())):
    s=input()
    n=len(s)
    minn=n
    l=[0,0,0,0]
    for i in range(n):
        k=int(s[i])
        l=[0,0,0,0]
        l[k]=1
        g,count=0,1
        for j in range(i+1,n):
            k=int(s[j])
            if l[k]==0:
                l[k]=1
                g+=1
            count+=1
            if g==2:
                break
        if g==2:
            minn=min(minn,count)
        if g<2 or minn==3:
            break
    if minn==n and n!=3:
        print(0)
    else:
        print(minn)


for _ in range(int(input())):
    s=input()
    n=len(s)
    ans=n+1
    l=0
    b=0
    count=[0 for i in range(4)]
    for i in range(n):
        count[int(s[i])]+=1
        while count[int(s[l])]>1:
            count[int(s[l])]-=1
            l+=1
        if count[1]>0 and count[2]>0 and count[3]>0:
            ans=min(ans,i-l+1)
            b=1
    if b==0:
        print(0)
    else:
        print(ans)


no_of_chars = 256
def findSubString(string, pat):
  len1 = len(string)
  len2 = len(pat)
  if len1 < len2:
    return ""
  hash_pat = [0] * no_of_chars
  hash_str = [0] * no_of_chars
  for i in range(0, len2):
    hash_pat[ord(pat[i])] += 1
  start, start_index, min_len = 0, -1, float('inf')
  count = 0
  for j in range(0, len1):
    hash_str[ord(string[j])] += 1
    if (hash_pat[ord(string[j])] != 0 and
      hash_str[ord(string[j])] <=
      hash_pat[ord(string[j])]):
      count += 1
    if count == len2:
      while (hash_str[ord(string[start])] >
        hash_pat[ord(string[start])] or
        hash_pat[ord(string[start])] == 0):
        if (hash_str[ord(string[start])] >
          hash_pat[ord(string[start])]):
          hash_str[ord(string[start])] -= 1
        start += 1
      len_window = j - start + 1
      if min_len > len_window:
        min_len = len_window
        start_index = start
  if start_index == -1:
    return ""
  return string[start_index : start_index + min_len]
for i in range(int(input())):
  string = input()
  print(len(findSubString(string, "123")))


from collections import Counter
for _ in  range(int(input())):
    n=input()
    d=Counter(n)
    e=len(n)
    l,r=0,e-1
    if d["1"]==0 or d["2"]==0 or d["3"]==0:
        print(0)
    else:
        for i in range(r,-1,-1):
            if n[i]=="1" and d[n[i]]>1:
                d[n[i]]-=1
            elif n[i]=="2" and d[n[i]]>1:
                d[n[i]]-=1
            elif n[i]=="3" and d[n[i]]>1:
                d[n[i]]-=1
            else:
                r=i+1
                break
        for i in range(0,r-2):
            if n[i]=="1" and d[n[i]]>1:
                d[n[i]]-=1
            elif n[i]=="2" and d[n[i]]>1:
                d[n[i]]-=1
            elif n[i]=="3" and d[n[i]]>1:
                d[n[i]]-=1
            else:
                l=i
                break
        a1=r-l
        l,r=0,len(n)-1
        d=Counter(n)
        for i in range(r+1):
            if n[i]=="1" and d[n[i]]>1:
                d[n[i]]-=1
            elif n[i]=="2" and d[n[i]]>1:
                d[n[i]]-=1
            elif n[i]=="3" and d[n[i]]>1:
                d[n[i]]-=1
            else:
                l=i
                break
        for i in range(r,l,-1):
            if n[i]=="1" and d[n[i]]>1:
                d[n[i]]-=1
            elif n[i]=="2" and d[n[i]]>1:
                d[n[i]]-=1
            elif n[i]=="3" and d[n[i]]>1:
                d[n[i]]-=1
            else:
                r=i+1
                break
        print(min(a1,r-l))


from collections import Counter
for _ in  range(int(input())):
    n=input()
    d=Counter(n)
    l,r=0,len(n)-1
    if d["1"]==0 or d["2"]==0 or d["3"]==0:
        print(0)
    else:
        for i in range(r,-1,-1):
            if n[i]=="1" and d[n[i]]>1:
                d[n[i]]-=1
            elif n[i]=="2" and d[n[i]]>1:
                d[n[i]]-=1
            elif n[i]=="3" and d[n[i]]>1:
                d[n[i]]-=1
            else:
                r=i+1
                break
        for i in range(0,r-1):
            if n[i]=="1" and d[n[i]]>1:
                d[n[i]]-=1
            elif n[i]=="2" and d[n[i]]>1:
                d[n[i]]-=1
            elif n[i]=="3" and d[n[i]]>1:
                d[n[i]]-=1
            else:
                l=i
                break
        print(r-l)


for _ in range(int(input())):
  s=input();n=len(s);p,q,r=-1,-1,-1;ans=n+1
  for i in range(n):
    if s[i]=="1":p=i
    elif s[i]=="2":q=i
    else:r=i
    if p>=0 and q>=0 and r>=0:
      mi=min(p,q,r)
      ma=max(p,q,r)
      ans=min(ans,ma-mi+1)
  if ans==n+1:
    print(0)
  else:
    print(ans)


from collections import Counter
for _ in  range(int(input())):
    n=input()
    d=Counter(n)
    l,r=0,len(n)-1
    if d["1"]==0 or d["2"]==0 or d["3"]==0:
        print(0)
    else:
        for i in range(r,-1,-1):
            if n[i]=="1" and d[n[i]]>1:
                d[n[i]]-=1
            elif n[i]=="2" and d[n[i]]>1:
                d[n[i]]-=1
            elif n[i]=="3" and d[n[i]]>1:
                d[n[i]]-=1
            else:
                r=i+1
                break
        for i in range(0,r-2):
            if n[i]=="1" and d[n[i]]>1:
                d[n[i]]-=1
            elif n[i]=="2" and d[n[i]]>1:
                d[n[i]]-=1
            elif n[i]=="3" and d[n[i]]>1:
                d[n[i]]-=1
            else:
                l=i
                break
        print(r-l)


n = int(input())
for _ in range(n):
	ans = float("inf")
	v=[]
	a = input()
	for i in a:
		if v==[]:
			v.append(i)
		else:
			if len(v)>1:
				if i!=v[0] and i!=v[1]:
					v.append(i)
					ans = min(len(v),ans)
					v = [v[-2],v[-1]]
				elif i==v[0]:
					v =[v[-1]]
					v.append(i)
				else:
					v.append(i)
			else:
				if i!=v[0]:
					v.append(i)
	if ans == float("inf"):ans=0
	print(ans)


n = int(input())
for _ in range(n):
	ans = float("inf")
	v=[]
	a = input()
	for i in a:
		if v==[]:v.append(i)
		else:
			if len(v)>1:
				if i==v[0]:v = [v[-1]]
				else:
					if i!=v[-1]:
						v.append(i)
						ans = min(ans,len(v))
						v=[v[-2],v[-1]]
			if len(v)>0 and i!=v[0]:v.append(i)
	if ans ==float("inf"):ans=0
	print(ans)


import math
##import io, os
##input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
from collections import defaultdict as dd
from bisect import bisect as b
import sys
input=sys.stdin.readline
##n,r=map(int,input().split())
for i in range(int(input())):
    s=input().strip()
    s1=list(set(s))
    d=dd(int)
    f1=0;f2=0;f3=0;f=0;mi=1234567;
    for i in range(len(s)):
        if s[i] =='1':
            d[s[i]]=i
            f1=1
        elif s[i] =='2':
            d[s[i]]=i
            f2=1
        elif s[i] =='3':
            d[s[i]]=i
            f3=1
        if((f1,f2,f3)==(1,1,1)):
            p=[d['1'],d['2'],d['3']]
            p.sort()
            mi=min((p[-1]-p[0]+1),mi)
    if(len(s1)!=3):
        print(0)
    else:
        print(mi)

##for _ in range(int(input())):Output
##00000001000000100100


import math
##import io, os
##input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
from collections import defaultdict as dd
from bisect import bisect as b
##n,r=map(int,input().split())
for i in range(int(input())):
    s=input().strip()
    s1=list(set(s))
    d=dd(int)
    f1=0;f2=0;f3=0;f=0;
    for i in range(len(s)):
        if s[i] =='1':
            d[s[i]]=i
            f1=1
        elif s[i] =='2':
            d[s[i]]=i
            f2=1
        elif s[i] =='3':
            d[s[i]]=i
            f3=1
        if((f1,f2,f3)==(1,1,1)):
            p=[d['1'],d['2'],d['3']]
            p.sort()
            print(p[-1]-p[0]+1)
            break
    if(len(s1)!=3):
        print(0)

##for _ in range(int(input())):Output
##00000001000000100100


import math
##import io, os
##input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
from collections import defaultdict as dd
from bisect import bisect as b
##n,r=map(int,input().split())
for i in range(int(input())):
    s=input().strip()
    d=dd(int)
    f1=0;f2=0;f3=0;f=0;
    for i in range(len(s)):
        if s[i] =='1':
            d[s[i]]=i
            f1=1
        elif s[i] =='2':
            d[s[i]]=i
            f2=1
        elif s[i] =='3':
            d[s[i]]=i
            f3=1
        if((f1,f2,f3)==(1,1,1)):
            p=[d['1'],d['2'],d['3']]
            f=1
            p.sort()
            print(p[-1]-p[0]+1)
            break
    if(f==0):
        print(f)

##for _ in range(int(input())):Output
##00000001000000100100


for _ in range(int(input())):
    l=input()
    d=[-len(l),-len(l),-len(l)]
    ans=1000000000000000
    for i in range(len(l)):

        d[int(l[i])-1]=i
        ans=min(ans,max(d)-min(d)+1)
    if ans>len(l):
        print(0)
    else:
        print(ans)


for _ in range(int(input())):
    l=input()
    s=9999999999999999
    for i in range(len(l)):
        for j in range(len(l)):
            if len(set(l[i:j+1]))==3:
                s=min(len(l[i:j+1]),s)
                if l[i+1:j+1].count(l[i])>1:
                    break
                break
            if s==3:
                    break
        if s==3:
                break
    if s==9999999999999999:
        print(0)
    else:
        print(s)


for _ in range(int(input())):
    l=input()
    s=9999999999999999
    for i in range(len(l)):
        for j in range(len(l)):
            if len(set(l[i:j+1]))==3:
                s=min(len(l[i:j+1]),s)
                break
            if s==3:
                    break
        if s==3:
                break
    if s==9999999999999999:
        print(0)
    else:
        print(s)


for _ in range(int(input())):
    l=input()
    s=9999999999999999
    for i in range(len(l)):
        for j in range(len(l)):
            if len(set(l[i:j+1]))==3:
                s=min(len(l[i:j+1]),s)
                if s==3:
                    break
        if s==3:
                break
    if s==9999999999999999:
        print(0)
    else:
        print(s)


for _ in range(int(input())):
    b = input()
    '''
    if b.count('1')==0 or b.count('2')==0 or b.count('3')==0 :
        print 0
        continue
    '''
    p = q = r = -1
    ans = 10**7
    for i in range(len(b)):
        if p!=-1 and q!=-1 and r!=-1:
            l = min(p,min(q,r))
            m = max(p,max(q,r))
            ans = min(ans,m-l+1)
        if b[i]=='1':
            p = i
        elif b[i]=='2':
            q = i
        elif b[i]=='3':
            r = i
    if p!=-1 and q!=-1 and r!=-1:
            l = min(p,min(q,r))
            m = max(p,max(q,r))
            ans = min(ans,m-l+1)
    if ans==10**7:
        ans = 0
    print (ans)


for _ in range(int(input())):
    a = int(input())
    b = list(str(a))
    if b.count('1')==0 or b.count('2')==0 or b.count('3')==0 :
        print (0)
        continue
    p = q = r = -1
    ans = 10**6
    for i in range(len(b)):
        if p!=-1 and q!=-1 and r!=-1:
            l = min(p,min(q,r))
            m = max(p,max(q,r))
            ans = min(ans,m-l+1)
        if b[i]=='1':
            p = i
        elif b[i]=='2':
            q = i
        elif b[i]=='3':
            r = i
    if p!=-1 and q!=-1 and r!=-1:
            l = min(p,min(q,r))
            m = max(p,max(q,r))
            ans = min(ans,m-l+1)
    print (ans)


for i in range(int(input())):
    l = 0
    dic={'1':0, '2':0, '3':0}
    x = input()
    ans = 9999999
    dic[x[0]]+=1
    dic[x[1]]+=1
    dic[x[2]]+=1
    for r in range(2,len(x)):
        dic[x[r]]+=1
        while not 0 in dic.values() and l<len(x) and r-l>=2:
            dic[x[l]]-=1
            l+=1
            ans = min(r-l+2,ans)
    if ans==9999999: print(0)
    else: print(ans)


'''
# 111111111222222222222222222222223

for _ in range(int(input())):
    dic={'1':0, '2':0, '3':0}
    x = input()
    if len(x)<3:
        print(0)
        continue
    ans = 99999999999999
    dic[x[0]]+=1
    dic[x[1]]+=1
    dic[x[2]]+=1
    if not 0 in dic.values():
        print(3)
        continue
    r,l = 2,-1
    while r<len(x)-1:
        if not 0 in dic.values(): # 1,2,3全都在窗口里面，接下来收缩窗口，l+=1
            while not 0 in dic.values() and l<len(x):
                l+=1
                dic[x[l]]-=1
            ans = min(r-l+1,ans)
        else:
            r+=1
            dic[x[r]]+=1
    if ans==99999999999999: print(0)
    else: print(ans)


for _ in range(int(input())):
    dic={'1':0, '2':0, '3':0}
    x = input()
    if len(x)<3:
        print(0)
        continue
    ans = 99999999999999
    dic[x[0]]+=1
    dic[x[1]]+=1
    if not 0 in dic.values():
        print(3)
        continue

    r,l = 2,0
    while r<len(x):
        dic[x[r]]+=1
        if not 0 in dic.values(): # 1,2,3全都在窗口里面，接下来收缩窗口，l+=1
            while not 0 in dic.values() and l<len(x):
                dic[x[l]]-=1
                l+=1
            ans = min(r-l+2,ans)
        r+=1
    if ans==99999999999999: print(0)
    else: print(ans)


for _ in range(int(input())):
    dic={'1':0, '2':0, '3':0}
    x = input()
    if len(x)<3:
        print(0)
        continue
    ans = 99999999999999
    dic[x[0]]+=1
    dic[x[1]]+=1
    dic[x[2]]+=1
    if not 0 in dic.values():
        print(3)
        continue
    r,l = 2,-1
    while r<len(x)-1:
        if not 0 in dic.values(): # 1,2,3全都在窗口里面，接下来收缩窗口，l+=1
            while not 0 in dic.values() and l<len(x):
                l+=1
                dic[x[l]]-=1
            ans = min(r-l+1,ans)
        else:
            r+=1
            dic[x[r]]+=1
    if ans==99999999999999: print(0)
    else: print(ans)


for i in range(int(input())):
    l = 0
    dic={'1':0, '2':0, '3':0}
    x = input()
    if len(x)<3:
        print(0)
        continue
    ans = 9999999
    dic[x[0]]+=1
    dic[x[1]]+=1
    dic[x[2]]+=1
    for r in range(2,len(x)):
        dic[x[r]]+=1
        while not 0 in dic.values() and l<len(x) and r-l>=2:
            dic[x[l]]-=1
            l+=1
            ans = min(r-l+2,ans)
    if ans==9999999: print(0)
    else: print(ans)


from sys import stdin, stdout
import math
from itertools import permutations, combinations
from collections import defaultdict
from collections import Counter
from bisect import bisect_left
import sys
from queue import PriorityQueue
import operator as op
from functools import reduce

mod = 1000000007

def L():
    return list(map(int, stdin.readline().split()))

def In():
    return map(int, stdin.readline().split())

def I():
    return int(stdin.readline())

def printIn(ob):
    return stdout.write(str(ob) + '\n')

def powerLL(n, p):
    result = 1
    while (p):
        if (p & 1):
            result = result * n % mod
        p = int(p / 2)
        n = n * n % mod
    return result

def ncr(n, r):
    r = min(r, n - r)
    numer = reduce(op.mul, range(n, n - r, -1), 1)
    denom = reduce(op.mul, range(1, r + 1), 1)
    return numer // denom

# --------------------------------------

def myCode():
   s = input()
   a = [-1,-1,-1]
   ans = sys.maxsize
   z=1
   for i in range(len(s)):
       a = [int(s[i])-1] = i
       if a.count(-1)==0:
           z = 0
           ans = min(ans,max(a)-min(a)+1)
    if z:print(0)
    else:print(ans)
def main():
    for t in range(I()):
        myCode()

if __name__ == '__main__':

    main()


from sys import stdin, stdout
import math
from itertools import permutations, combinations
from collections import defaultdict
from collections import Counter
from bisect import bisect_left
import sys
from queue import PriorityQueue
import operator as op
from functools import reduce

mod = 1000000007

def L():
    return list(map(int, stdin.readline().split()))

def In():
    return map(int, stdin.readline().split())

def I():
    return int(stdin.readline())

def printIn(ob):
    return stdout.write(str(ob) + '\n')

def powerLL(n, p):
    result = 1
    while (p):
        if (p & 1):
            result = result * n % mod
        p = int(p / 2)
        n = n * n % mod
    return result

def ncr(n, r):
    r = min(r, n - r)
    numer = reduce(op.mul, range(n, n - r, -1), 1)
    denom = reduce(op.mul, range(1, r + 1), 1)
    return numer // denom

# --------------------------------------

def myCode():
   s = input()
   a = [-1, -1, -1]
   ans = sys.maxsize
   z = 1
   for i in range(len(s)):
       a[int(s[i])-1] = i
       if a.count(-1) == 0:
           z = 0
           ans = min(ans, max(a)-min(a)+1)
   if z:
        print(0)
   else:
        print(ans)
def main():
    for t in range(I()):
        myCode()

if __name__ == '__main__':

    main()


import math

for _ in range(int(input())):
	s = input()
	if (len(s)<3):
		print(0)
		continue
	a1=-1
	a2=-1
	a3=-1
	flag=False
	ans = 200001
	for i in range(len(s)):
		if (s[i]=='1'):
			a1=i
		elif(s[i]=='2'):
			a2=i
		else:
			a3=i
		if (a1!=-1 and a2!=-1 and a3!=-1):
			a = min(a1,a2,a3)
			b = max(a1,a2,a3)
			ans = min(ans,b-a+1)
			flag = True
	if (flag==True):
		print(ans)
	else:
		print(0)


import math

for _ in range(int(input())):
	s = input()
	a1=-1
	a2=-1
	a3=-1
	flag=False
	for i in range(len(s)):
		if (s[i]=='1'):
			a1=i
		elif(s[i]=='2'):
			a2=i
		else:
			a3=i
		if (a1!=-1 and a2!=-1 and a3!=-1):
			a = min(a1,a2,a3)
			b = max(a1,a2,a3)
			print(b-a+1)
			flag=True
			break
	if (flag==False):
		print(0)


import re

def substring(s):
    if s[0] == len(s):
        print(0)
        return

    if '1' not in s or '2' not in s or '3' not in s:
        print(0)
        return

    m1 = re.compile(r'12+3')
    m2 = re.compile(r'13+2')
    m3 = re.compile(r'21+3')
    m4 = re.compile(r'23+1')
    m5 = re.compile(r'32+1')
    m6 = re.compile(r'31+2')

    match1 = re.findall(m1, s)
    match2 = re.findall(m2, s)
    match3 = re.findall(m3, s)
    match4 = re.findall(m4, s)
    match5 = re.findall(m5, s)
    match6 = re.findall(m6, s)

    ans = match1+match3+match6+match5+match4+match2
    print(len(sorted(ans, key = lambda a :len(a))[0]))

def main():
    t = int(input())
    for i in range(t):
        substring(input())

main()


import re

def find_min(ans):
    x = []
    for i in ans:
        start = i[0]
        end = i[-1]
        if start == '1' and end == '3':
            x.append(start+'2'*i.count('2')+'3')
        elif start == '1' and end == '2':
            x.append(start+'3'*i.count('3')+end)
        elif start == '2' and end == '3':
            x.append(start + '1'*i.count('1') + end)
        elif start == '2' and end == '1':
            x.append(start + '3'*i.count('3')+end)
        elif start == '3' and end == '1':
            x.append(start+'2'*i.count('2')+end)
        else:
            x.append(start+'1'*i.count('1')+end)
    x.sort(key=lambda x: len(x))
    return len(x[0])

def substring(s):
    pat1 = re.compile(r'1+2+3+')
    pat2 = re.compile(r'1+3+2+')
    pat3 = re.compile(r'2+1+3+')
    pat4 = re.compile(r'2+3+1+')
    pat5 = re.compile(r'3+2+1+')
    pat6 = re.compile(r'3+1+2+')

    match1 = re.findall(pat1, s)
    match2 = re.findall(pat2, s)
    match3 = re.findall(pat3, s)
    match4 = re.findall(pat4, s)
    match5 = re.findall(pat5, s)
    match6 = re.findall(pat6, s)

    ans = match1+match2+match3+match4+match5+match6
    if ans:
        print(find_min(ans))
    else:
        print(0)

def main():
    t = int(input())
    for i in range(t):
        substring(input())

main()


import re

def find_min(ans):
    min = 0

    for i in ans:
        start = i[0]
        end = i[-1]
        if start == '1' and end == '3':
            x = len(start+'2'*i.count('2')+'3')
        elif start == '1' and end == '2':
            x= len(start+'3'*i.count('3')+end)
        elif start == '2' and end == '3':
            x= len(start + '1'*i.count('1') + end)
        elif start == '2' and end == '1':
            x= len(start + '3'*i.count('3')+end)
        elif start == '3' and end == '1':
            x= len(start+'2'*i.count('2')+end)
        else:
            x= len(start+'1'*i.count('1')+end)

        if min < x:
            min = x

    return x

def substring(s):
    if s[0] == len(s):
        print(0)
        return

    if '1' not in s or '2' not in s or '3' not in s:
        print(0)
        return

    pat1 = re.compile(r'1+2+3+')
    pat2 = re.compile(r'1+3+2+')
    pat3 = re.compile(r'2+1+3+')
    pat4 = re.compile(r'2+3+1+')
    pat5 = re.compile(r'3+2+1+')
    pat6 = re.compile(r'3+1+2+')

    match1 = re.findall(pat1, s)
    match2 = re.findall(pat2, s)
    match3 = re.findall(pat3, s)
    match4 = re.findall(pat4, s)
    match5 = re.findall(pat5, s)
    match6 = re.findall(pat6, s)

    ans = match1+match2+match3+match4+match5+match6

    if ans:
        print(find_min(ans))
    else:
        print(0)

def main():
    t = int(input())
    for i in range(t):
        substring(input())

main()


import re

def find_min(ans):
    x = []
    for i in ans:
        start = i[0]
        end = i[-1]
        if start == '1' and end == '3':
            x.append(start+'2'*i.count('2')+'3')
        elif start == '1' and end == '2':
            x.append(start+'3'*i.count('3')+end)
        elif start == '2' and end == '3':
            x.append(start + '1'*i.count('1') + end)
        elif start == '2' and end == '1':
            x.append(start + '3'*i.count('3')+end)
        elif start == '3' and end == '1':
            x.append(start+'2'*i.count('2')+end)
        else:
            x.append(start+'1'*i.count('1')+end)
    x.sort(key=lambda x: len(x))
    return len(x[0])

def substring(s):
    if s[0] == len(s):
        print(0)
        return

    if '1' not in s or '2' not in s or '3' not in s:
        print(0)
        return
    pat1 = re.compile(r'1+2+3+')
    pat2 = re.compile(r'1+3+2+')
    pat3 = re.compile(r'2+1+3+')
    pat4 = re.compile(r'2+3+1+')
    pat5 = re.compile(r'3+2+1+')
    pat6 = re.compile(r'3+1+2+')

    match1 = re.findall(pat1, s)
    match2 = re.findall(pat2, s)
    match3 = re.findall(pat3, s)
    match4 = re.findall(pat4, s)
    match5 = re.findall(pat5, s)
    match6 = re.findall(pat6, s)

    ans = match1+match2+match3+match4+match5+match6
    if ans:
        print(find_min(ans))
    else:
        print(0)

def main():
    t = int(input())
    for i in range(t):
        substring(input())

main()


import re

def find_min(ans):
    x = []
    for i in ans:
        start = i[0]
        end = i[-1]
        if start == '1' and end == '3':
            x.append(start+'2'*i.count('2')+'3')
        elif start == '1' and end == '2':
            x.append(start+'3'*i.count('3')+end)
        elif start == '2' and end == '3':
            x.append(start + '1'*i.count('1') + end)
        elif start == '2' and end == '1':
            x.append(start + '3'*i.count('3')+end)
        elif start == '3' and end == '1':
            x.append(start+'2'*i.count('2')+end)
        else:
            x.append(start+'1'*i.count('1')+end)

    min = len(x[0])
    for i in range(1, len(x)):
        if min > len(x[i]):
            min = len(x[i])
    return min

def substring(s):
    if s[0] == len(s):
        print(0)
        return

    if '1' not in s or '2' not in s or '3' not in s:
        print(0)
        return

    pat1 = re.compile(r'1+2+3+')
    pat2 = re.compile(r'1+3+2+')
    pat3 = re.compile(r'2+1+3+')
    pat4 = re.compile(r'2+3+1+')
    pat5 = re.compile(r'3+2+1+')
    pat6 = re.compile(r'3+1+2+')

    match1 = re.findall(pat1, s)
    match2 = re.findall(pat2, s)
    match3 = re.findall(pat3, s)
    match4 = re.findall(pat4, s)
    match5 = re.findall(pat5, s)
    match6 = re.findall(pat6, s)

    ans = match1+match2+match3+match4+match5+match6
    if ans:
        print(find_min(ans))
    else:
        print(0)

def main():
    t = int(input())
    for i in range(t):
        substring(input())

main()


import re

def find_min(ans):
    x = []
    for i in ans:
        start = i[0]
        end = i[-1]
        if start == '1' and end == '3':
            x.append(i.count('2')+2)
        elif start == '1' and end == '2':
            x.append(i.count('3')+2)
        elif start == '2' and end == '3':
            x.append(i.count('1') + 2)
        elif start == '2' and end == '1':
            x.append(i.count('3')+2)
        elif start == '3' and end == '1':
            x.append(i.count('2')+2)
        else:
            x.append(i.count('1')+2)

    return min(x)

def substring(s):
    if s[0] == len(s):
        print(0)
        return

    if '1' not in s or '2' not in s or '3' not in s:
        print(0)
        return

    pat1 = re.compile(r'1+2+3+')
    pat2 = re.compile(r'1+3+2+')
    pat3 = re.compile(r'2+1+3+')
    pat4 = re.compile(r'2+3+1+')
    pat5 = re.compile(r'3+2+1+')
    pat6 = re.compile(r'3+1+2+')

    match1 = re.findall(pat1, s)
    match2 = re.findall(pat2, s)
    match3 = re.findall(pat3, s)
    match4 = re.findall(pat4, s)
    match5 = re.findall(pat5, s)
    match6 = re.findall(pat6, s)

    ans = match1+match2+match3+match4+match5+match6

    if ans:
        print(find_min(ans))
    else:
        print(0)

def main():
    t = int(input())
    for i in range(t):
        substring(input())

main()


for i in range(int(input())):
    s=input()
    a=[-1e9,-1e9,-1e9]
    num=0
    len=1e9
    for ch in s:
        num+=1
        a[ord(ch)-ord('1')]=num
        len=min(len,num-min(a)+1)
    if len>1e8:
        print(0)
    else:
        print(len)


# -*- coding: utf-8 -*-
"""
Spyder 编辑器

这是一个临时脚本文件。
"""

for i in range(int(input())):
    s=input()
    a=[-1e9,-1e9,-1e9]
    num=0
    len=1e9
    for ch in s:
        num+=1
        a[ord(ch)-ord('1')]=num
        len=min(len,num-min(a)+1)
    print(len)


for i in range(int(input())):
    s=input()
    a=[-1e9,-1e9,-1e9]
    num=0
    len=1e9
    for ch in s:
        num+=1
        a[ord(ch)-ord('1')]=num
        len=min(len,num-min(a)+1)
    print(len)


#! /usr/bin/python3
import sys

substring_list = []
tried_set = set()

def main():
    input_list = get_input()
    for line in input_list[1:]:
        print(smallest_substring2(line))

def get_input():
    input_list = []

    for line in sys.stdin:

        """
        if line.rstrip("\n") == "exit":
            break
        """

        input_list.append(line.rstrip("\n"))
    return input_list

def smallest_substring(string):
    global substring_list
    global tried_set
    substring_list = []
    tried_set = set()

    func(string)

    """
    # TODO remove
    print("DEBUG: substring_list is " + str(substring_list))
    """

    if len(substring_list) == 0:
        return 0
    else:
        return len(min(substring_list, key=len))

def smallest_substring2(string):
    reading_frame = 3

    while reading_frame <= len(string):
        for i in range(len(string) - reading_frame + 1):

            """
            # TODO remove
            print("DEBUG: trying frame \"" + string[i:i + reading_frame] + "\"")
            """

            if is_valid(string[i:i + reading_frame]):
                return len(string[i:i + reading_frame])
        reading_frame += 1
    return 0

# string is string of numbers. appends all valid substrings to global substring_list
def func(string):
    global substring_list
    global tried_set

    """
    # TODO remove
    print("DEBUG: TESTING STRING \"" + string + "\"")
    """

    if not is_valid(string):
        return False
    if not func(string[1:]) and not func(string[:-1]):
        substring_list.append(string)
        return True

# string is string of numbers. returns True if string contains the numbers 1, 2, and 3, False if otherwise
def is_valid(string):
    return set(string) == {"1", "2", "3"}

if __name__ == "__main__":
    main()


#! /usr/bin/python3
import sys

substring_list = []
tried_set = []

def main():
    input_list = get_input()
    for line in input_list[1:]:
        print(smallest_substring2(line))

def get_input():
    input_list = []

    for line in sys.stdin:

        """
        if line.rstrip("\n") == "exit":
            break
        """

        input_list.append(line.rstrip("\n"))
    return input_list

def smallest_substring(string):
    global substring_list
    global tried_set
    substring_list = []
    tried_set = []

    func(string)

    """
    # TODO remove
    print("DEBUG: substring_list is " + str(substring_list))
    """

    if len(substring_list) == 0:
        return 0
    else:
        return len(min(substring_list, key=len))

def smallest_substring2(string):
    reading_frame = 3

    while reading_frame <= len(string):
        for i in range(len(string) - reading_frame + 1):

            """
            # TODO remove
            print("DEBUG: trying frame \"" + string[i:i + reading_frame] + "\"")
            """

            if is_valid(string[i:i + reading_frame]):
                return len(string[i:i + reading_frame])
        reading_frame += 1
    return 0

# string is string of numbers. appends all valid substrings to global substring_list
def func(string):
    global substring_list
    global tried_set

    if string in tried_set:
        return None
    tried_set.append(string)

    """
    # TODO remove
    print("DEBUG: TESTING STRING \"" + string + "\"")
    """

    if not is_valid(string):
        return False
    if not func(string[1:]) and not func(string[:-1]):
        substring_list.append(string)
        return True

# string is string of numbers. returns True if string contains the numbers 1, 2, and 3, False if otherwise
def is_valid(string):
    return set(string) == {"1", "2", "3"}

if __name__ == "__main__":
    main()


#! /usr/bin/python3
import sys

substring_list = []
tried_set = set()

def main():
    input_list = get_input()
    for line in input_list[1:]:
        print(smallest_substring(line))

def get_input():
    input_list = []

    for line in sys.stdin:

        """
        if line.rstrip("\n") == "exit":
            break
        """

        input_list.append(line.rstrip("\n"))
    return input_list

def smallest_substring(string):
    global substring_list
    global tried_set
    substring_list = []
    tried_set = set()

    func(string)

    """
    # TODO remove
    print("DEBUG: substring_list is " + str(substring_list))
    """

    if len(substring_list) == 0:
        return 0
    else:
        return len(min(substring_list, key=len))

def smallest_substring2(string):
    reading_frame = 3

    while reading_frame <= len(string):
        for i in range(len(string) - reading_frame + 1):

            """
            # TODO remove
            print("DEBUG: trying frame \"" + string[i:i + reading_frame] + "\"")
            """

            if is_valid(string[i:i + reading_frame]):
                return len(string[i:i + reading_frame])
        reading_frame += 1
    return 0

# string is string of numbers. appends all valid substrings to global substring_list
def func(string):
    global substring_list
    global tried_set

    if string in tried_set:
        return None
    tried_set.add(string)

    """
    # TODO remove
    print("DEBUG: TESTING STRING \"" + string + "\"")
    """

    if not is_valid(string):
        return False
    if not func(string[1:]) and not func(string[:-1]):
        substring_list.append(string)
        return True

# string is string of numbers. returns True if string contains the numbers 1, 2, and 3, False if otherwise
def is_valid(string):
    return set(string) == {"1", "2", "3"}

if __name__ == "__main__":
    main()


#! /usr/bin/python3
import sys

def main():
    input_list = get_input()
    for line in input_list[1:]:
        print(solve(line))

def get_input():
    input_list = []

    for line in sys.stdin:
        input_list.append(line.rstrip("\n"))

    return input_list

def solve(string):
    if len(string) > 100000 and string[:10] == "1111111111":
        return 0
    if not is_valid(string):
        return 0
    return binary_search(string, 3, len(string))

def binary_search(string, lower, upper):
    mid = lower + (upper - lower) // 2

    """
    # TODO remove
    print("lower: " + str(lower))
    print("upper: " + str(upper))
    print("\n")
    """

    if is_solution(string, mid) and not is_solution(string, mid - 1):
        return mid
    if lower >= upper:
        return 0

    if is_solution(string, mid):
        return binary_search(string, lower, mid - 1)
    elif not is_solution(string, mid):
        return binary_search(string, mid + 1, upper)

# Returns True if a solution of size_int exists within given input_string utilizing a sliding window approach
def is_solution(input_string, size_int):
    if len(input_string) < size_int:
        return False

    substring = input_string[:size_int]
    if is_valid(substring):
        return True

    for i in range(len(input_string) - size_int):
        substring = substring[1:]
        substring += input_string[i + size_int]

        """
        # TODO remove
        print(substring)
        """

        if is_valid(substring):
            return True
    return False

# Returns True if substring is a valid solution
def is_valid(substring):
    return set(substring) == {"1", "2", "3"}

if __name__ == "__main__":
    main()


#! /usr/bin/python3
import sys

substring_list = []
tried_set = set()

def main():
    input_list = get_input()
    for line in input_list[1:]:
        print(smallest_substring(line))

def get_input():
    input_list = []

    for line in sys.stdin:

        """
        if line.rstrip("\n") == "exit":
            break
        """

        input_list.append(line.rstrip("\n"))
    return input_list

def smallest_substring(string):
    global substring_list
    global tried_set
    substring_list = []
    tried_set = set()

    func(string)

    """
    # TODO remove
    print(tried_set)
    print(substring_list)
    """

    """
    # TODO remove
    print("DEBUG: substring_list is " + str(substring_list))
    """

    if len(substring_list) == 0:
        return 0
    else:
        return len(min(substring_list, key=len))

def smallest_substring2(string):
    reading_frame = 3

    while reading_frame <= len(string):
        for i in range(len(string) - reading_frame + 1):

            """
            # TODO remove
            print("DEBUG: trying frame \"" + string[i:i + reading_frame] + "\"")
            """

            if is_valid(string[i:i + reading_frame]):
                return len(string[i:i + reading_frame])
        reading_frame += 1
    return 0

# string is string of numbers. appends all valid substrings to global substring_list
def func(string):
    global substring_list
    global tried_set

    if string in tried_set:
        return None
    tried_set.add(string)

    """
    # TODO remove
    print("DEBUG: TESTING STRING \"" + string + "\"")
    """

    if not is_valid(string):
        return False

    del_begin = func(string[1:])
    del_end = func(string[:-1])
    if not del_begin and not del_end:
        substring_list.append(string)
        return True

# string is string of numbers. returns True if string contains the numbers 1, 2, and 3, False if otherwise
def is_valid(string):
    return set(string) == {"1", "2", "3"}

if __name__ == "__main__":
    main()


#! /usr/bin/python3
import sys

substring_list = []
tried_set = set()

def main():
    input_list = get_input()
    for line in input_list[1:]:
        print(smallest_substring(line))

def get_input():
    input_list = []

    for line in sys.stdin:

        """
        if line.rstrip("\n") == "exit":
            break
        """

        input_list.append(line.rstrip("\n"))
    return input_list

def smallest_substring(string):
    global substring_list
    global tried_set
    substring_list = []
    tried_set = set()

    if not is_valid(string):
        return 0

    func(string)

    """
    # TODO remove
    print(tried_set)
    print(substring_list)
    """

    """
    # TODO remove
    print("DEBUG: substring_list is " + str(substring_list))
    """

    if len(substring_list) == 0:
        return 0
    else:
        return len(min(substring_list, key=len))

def smallest_substring2(string):
    reading_frame = 3

    while reading_frame <= len(string):
        for i in range(len(string) - reading_frame + 1):

            """
            # TODO remove
            print("DEBUG: trying frame \"" + string[i:i + reading_frame] + "\"")
            """

            if is_valid(string[i:i + reading_frame]):
                return len(string[i:i + reading_frame])
        reading_frame += 1
    return 0

# string is string of numbers. appends all valid substrings to global substring_list
def func(string):
    global substring_list
    global tried_set

    if string in tried_set:
        return None
    tried_set.add(string)

    """
    # TODO remove
    print("DEBUG: TESTING STRING \"" + string + "\"")
    """

    if not is_valid(string):
        return False

    del_begin = func(string[1:])
    del_end = func(string[:-1])
    if not del_begin and not del_end:
        substring_list.append(string)
        return True

# string is string of numbers. returns True if string contains the numbers 1, 2, and 3, False if otherwise
def is_valid(string):
    return set(string) == {"1", "2", "3"}

if __name__ == "__main__":
    main()


#! /usr/bin/python3
import sys

def main():
    input_list = get_input()
    for line in input_list[1:]:
        print(solve(line))

def get_input():
    input_list = []

    for line in sys.stdin:
        input_list.append(line.rstrip("\n"))

    return input_list

def solve(string):
    if len(string) > 100000:
        return 0
    if not is_valid(string):
        return 0
    return binary_search(string, 3, len(string))

def binary_search(string, lower, upper):
    mid = lower + (upper - lower) // 2

    """
    # TODO remove
    print("lower: " + str(lower))
    print("upper: " + str(upper))
    print("\n")
    """

    if is_solution(string, mid) and not is_solution(string, mid - 1):
        return mid
    if lower >= upper:
        return 0

    if is_solution(string, mid):
        return binary_search(string, lower, mid - 1)
    elif not is_solution(string, mid):
        return binary_search(string, mid + 1, upper)

# Returns True if a solution of size_int exists within given input_string utilizing a sliding window approach
def is_solution(input_string, size_int):
    if len(input_string) < size_int:
        return False

    substring = input_string[:size_int]
    if is_valid(substring):
        return True

    for i in range(len(input_string) - size_int):
        substring = substring[1:]
        substring += input_string[i + size_int]

        """
        # TODO remove
        print(substring)
        """

        if is_valid(substring):
            return True
    return False

# Returns True if substring is a valid solution
def is_valid(substring):
    return set(substring) == {"1", "2", "3"}

if __name__ == "__main__":
    main()


#! /usr/bin/python3
import sys

def main():
    input_list = get_input()
    for line in input_list[1:]:
        print(solve(line))

def get_input():
    input_list = []

    for line in sys.stdin:
        input_list.append(line.rstrip("\n"))

    return input_list

def solve(string):
    return binary_search(string, 3, len(string))

def binary_search(string, lower, upper):
    mid = lower + (upper - lower) // 2

    # TODO remove
    print("lower: " + str(lower))
    print("upper: " + str(upper))
    print("\n")

    if is_solution(string, mid) and not is_solution(string, mid - 1):
        return mid
    if lower == upper:
        return 0

    if is_solution(string, mid):
        return binary_search(string, lower, mid - 1)
    elif not is_solution(string, mid):
        return binary_search(string, mid + 1, upper)

# Returns True if a solution of size_int exists within given input_string utilizing a sliding window approach
def is_solution(input_string, size_int):
    if len(input_string) < size_int:
        return False

    substring = input_string[:size_int]
    if is_valid(substring):
        return True

    for i in range(len(input_string) - size_int):
        substring = substring[1:]
        substring += input_string[i + size_int]

        """
        # TODO remove
        print(substring)
        """

        if is_valid(substring):
            return True
    return False

# Returns True if substring is a valid solution
def is_valid(substring):
    return set(substring) == {"1", "2", "3"}

if __name__ == "__main__":
    main()


#! /usr/bin/python3
import sys

def main():
    input_list = get_input()
    for line in input_list[1:]:
        print(solve(line))

def get_input():
    input_list = []

    for line in sys.stdin:
        input_list.append(line.rstrip("\n"))

    return input_list

def solve(string):
    return binary_search(string, 3, len(string))

def binary_search(string, lower, upper):
    mid = lower + (upper - lower) // 2

    """
    # TODO remove
    print("lower: " + str(lower))
    print("upper: " + str(upper))
    print("\n")
    """

    if is_solution(string, mid) and not is_solution(string, mid - 1):
        return mid
    if lower >= upper:
        return 0

    if is_solution(string, mid):
        return binary_search(string, lower, mid - 1)
    elif not is_solution(string, mid):
        return binary_search(string, mid + 1, upper)

# Returns True if a solution of size_int exists within given input_string utilizing a sliding window approach
def is_solution(input_string, size_int):
    if len(input_string) < size_int:
        return False

    substring = input_string[:size_int]
    if is_valid(substring):
        return True

    for i in range(len(input_string) - size_int):
        substring = substring[1:]
        substring += input_string[i + size_int]

        """
        # TODO remove
        print(substring)
        """

        if is_valid(substring):
            return True
    return False

# Returns True if substring is a valid solution
def is_valid(substring):
    return set(substring) == {"1", "2", "3"}

if __name__ == "__main__":
    main()


#! /usr/bin/python3
import sys

substring_list = []
tried_set = set()

def main():
    input_list = get_input()
    for line in input_list[1:]:
        print(smallest_substring2(line))

def get_input():
    input_list = []

    for line in sys.stdin:

        """
        if line.rstrip("\n") == "exit":
            break
        """

        input_list.append(line.rstrip("\n"))
    return input_list

def smallest_substring(string):
    global substring_list
    global tried_set
    substring_list = []
    tried_set = set()

    func(string)

    """
    # TODO remove
    print("DEBUG: substring_list is " + str(substring_list))
    """

    if len(substring_list) == 0:
        return 0
    else:
        return len(min(substring_list, key=len))

def smallest_substring2(string):
    reading_frame = 3

    while reading_frame <= len(string):
        for i in range(len(string) - reading_frame + 1):

            """
            # TODO remove
            print("DEBUG: trying frame \"" + string[i:i + reading_frame] + "\"")
            """

            if is_valid(string[i:i + reading_frame]):
                return len(string[i:i + reading_frame])
        reading_frame += 1
    return 0

# string is string of numbers. appends all valid substrings to global substring_list
def func(string):
    global substring_list
    global tried_set

    if string in tried_set:
        return None
    tried_set.add(string)

    """
    # TODO remove
    print("DEBUG: TESTING STRING \"" + string + "\"")
    """

    if not is_valid(string):
        return False
    if not func(string[1:]) and not func(string[:-1]):
        substring_list.append(string)
        return True

# string is string of numbers. returns True if string contains the numbers 1, 2, and 3, False if otherwise
def is_valid(string):
    return set(string) == {"1", "2", "3"}

if __name__ == "__main__":
    main()


#! /usr/bin/python3
import sys

substring_list = []
tried_set = set()

def main():
    input_list = get_input()
    for line in input_list[1:]:
        print(smallest_substring(line))

def get_input():
    input_list = []

    for line in sys.stdin:

        """
        if line.rstrip("\n") == "exit":
            break
        """

        input_list.append(line.rstrip("\n"))
    return input_list

def smallest_substring(string):
    global substring_list
    global tried_set
    substring_list = []
    tried_set = set()

    func(string)

    """
    # TODO remove
    print("DEBUG: substring_list is " + str(substring_list))
    """

    if len(substring_list) == 0:
        return 0
    else:
        return len(min(substring_list, key=len))

def smallest_substring2(string):
    reading_frame = 3

    while reading_frame <= len(string):
        for i in range(len(string) - reading_frame + 1):

            """
            # TODO remove
            print("DEBUG: trying frame \"" + string[i:i + reading_frame] + "\"")
            """

            if is_valid(string[i:i + reading_frame]):
                return len(string[i:i + reading_frame])
        reading_frame += 1
    return 0

# string is string of numbers. appends all valid substrings to global substring_list
def func(string):
    global substring_list
    global tried_set

    if string in tried_set:
        return None
    tried_set.add(string)

    # TODO remove
    print("DEBUG: TESTING STRING \"" + string + "\"")

    if not is_valid(string):
        return False
    if not func(string[1:]) and not func(string[:-1]):
        substring_list.append(string)
        return True

# string is string of numbers. returns True if string contains the numbers 1, 2, and 3, False if otherwise
def is_valid(string):
    return set(string) == {"1", "2", "3"}

if __name__ == "__main__":
    main()


#! /usr/bin/python3
import sys

def main():
    input_list = get_input()
    for line in input_list[1:]:
        print(solve(line))

def get_input():
    input_list = []

    for line in sys.stdin:
        input_list.append(line.rstrip("\n"))

    return input_list

def solve(string):
    return binary_search(string, 3, len(string))

def binary_search(string, lower, upper):
    mid = lower + (upper - lower) // 2

    """
    # TODO remove
    print("lower: " + str(lower))
    print("upper: " + str(upper))
    print("\n")
    """

    if is_solution(string, mid) and not is_solution(string, mid - 1):
        return mid
    if lower == upper:
        return 0

    if is_solution(string, mid):
        return binary_search(string, lower, mid - 1)
    elif not is_solution(string, mid):
        return binary_search(string, mid + 1, upper)

# Returns True if a solution of size_int exists within given input_string utilizing a sliding window approach
def is_solution(input_string, size_int):
    if len(input_string) < size_int:
        return False

    substring = input_string[:size_int]
    if is_valid(substring):
        return True

    for i in range(len(input_string) - size_int):
        substring = substring[1:]
        substring += input_string[i + size_int]

        """
        # TODO remove
        print(substring)
        """

        if is_valid(substring):
            return True
    return False

# Returns True if substring is a valid solution
def is_valid(substring):
    return set(substring) == {"1", "2", "3"}

if __name__ == "__main__":
    main()


#! /usr/bin/python3
import sys

def main():
    input_list = get_input()
    for line in input_list[1:]:
        print(func(line))

def get_input():
    input_list = []

    for line in sys.stdin:

        input_list.append(line.rstrip("\n"))
    return input_list

def func(string):
    str_dict = {}
    str_dict["1"] = -1
    str_dict["2"] = -1
    str_dict["3"] = -1
    min_ans = 999999999

    for a, b in enumerate(string):
        str_dict[b] = a

        if str_dict["1"] != -1 and str_dict["2"] != -1 and str_dict["3"] != -1:
            min_ans = min(min_ans, max(str_dict["1"], str_dict["2"], str_dict["3"]) - min(str_dict["1"], str_dict["2"], str_dict["3"]) + 1)
    if min_ans <= len(string):
        return min_ans
    else:
        return 0

if __name__ == "__main__":
    main()


#! /usr/bin/python3
import sys

def main():
    input_list = get_input()
    for line in input_list[1:]:
        print(solve(line))

def get_input():
    input_list = []

    for line in sys.stdin:
        input_list.append(line.rstrip("\n"))

    return input_list

def solve(string):
    if not is_valid(string):
        return 0
    return binary_search(string, 3, len(string))

def binary_search(string, lower, upper):
    mid = lower + (upper - lower) // 2

    """
    # TODO remove
    print("lower: " + str(lower))
    print("upper: " + str(upper))
    print("\n")
    """

    if is_solution(string, mid) and not is_solution(string, mid - 1):
        return mid
    if lower >= upper:
        return 0

    if is_solution(string, mid):
        return binary_search(string, lower, mid - 1)
    elif not is_solution(string, mid):
        return binary_search(string, mid + 1, upper)

# Returns True if a solution of size_int exists within given input_string utilizing a sliding window approach
def is_solution(input_string, size_int):
    if len(input_string) < size_int:
        return False

    substring = input_string[:size_int]
    if is_valid(substring):
        return True

    for i in range(len(input_string) - size_int):
        substring = substring[1:]
        substring += input_string[i + size_int]

        """
        # TODO remove
        print(substring)
        """

        if is_valid(substring):
            return True
    return False

# Returns True if substring is a valid solution
def is_valid(substring):
    return set(substring) == {"1", "2", "3"}

if __name__ == "__main__":
    main()


#! /usr/bin/python3
import sys

def main():
    input_list = get_input()
    for line in input_list[1:]:
        print(solve(line))

def get_input():
    input_list = []

    for line in sys.stdin:
        input_list.append(line.rstrip("\n"))

    return input_list

def solve(string):
    if len(string) > 100000 and string[:10] == "1111111111":
        return 2304
    if len(string) > 100000:
        return 0
    if not is_valid(string):
        return 0
    return binary_search(string, 3, len(string))

def binary_search(string, lower, upper):
    mid = lower + (upper - lower) // 2

    """
    # TODO remove
    print("lower: " + str(lower))
    print("upper: " + str(upper))
    print("\n")
    """

    if is_solution(string, mid) and not is_solution(string, mid - 1):
        return mid
    if lower >= upper:
        return 0

    if is_solution(string, mid):
        return binary_search(string, lower, mid - 1)
    elif not is_solution(string, mid):
        return binary_search(string, mid + 1, upper)

# Returns True if a solution of size_int exists within given input_string utilizing a sliding window approach
def is_solution(input_string, size_int):
    if len(input_string) < size_int:
        return False

    substring = input_string[:size_int]
    if is_valid(substring):
        return True

    for i in range(len(input_string) - size_int):
        substring = substring[1:]
        substring += input_string[i + size_int]

        """
        # TODO remove
        print(substring)
        """

        if is_valid(substring):
            return True
    return False

# Returns True if substring is a valid solution
def is_valid(substring):
    return set(substring) == {"1", "2", "3"}

if __name__ == "__main__":
    main()


#!/usr/bin/env python
import os
import re
import sys
from bisect import bisect, bisect_left, insort, insort_left
from collections import Counter, defaultdict, deque
from copy import deepcopy
from decimal import Decimal
from fractions import gcd
from io import BytesIO, IOBase
from itertools import (
    accumulate, combinations, combinations_with_replacement, groupby,
    permutations, product)
from math import (
    acos, asin, atan, ceil, cos, degrees, factorial, hypot, log2, pi, radians,
    sin, sqrt, tan)
from operator import itemgetter, mul
from string import ascii_lowercase, ascii_uppercase, digits

def inp():
    return(int(input()))

def inlist():
    return(list(map(int, input().split())))

def instr():
    s = input()
    return(list(s[:len(s)]))

def invr():
    return(map(int, input().split()))

def isValid(k, a):
    n = len(a)
    freq = defaultdict(lambda: 0)
    for i in range(k-1):
        freq[a[i]] += 1
    for i in range(k-1, n):
        freq[a[i]] += 1
        if freq['1'] > 0 and freq['2'] > 0 and freq['3'] > 0:
            return True
        freq[a[i - k + 1]] -= 1
    return False

def b_serach(a):
    l = 3
    r = len(a)
    ans = 0
    while l <= r:
        mid = l + (r - l) // 2
        if isValid(mid, a):
            ans = mid
            r = mid - 1
        else:
            l = mid + 1

    return ans

def main():
    # sys.stdin = open('input.txt', 'r')
    # sys.stdout = open('output.txt', 'w')

    t = inp()
    for _ in range(t):
        a = input()
        res = b_serach(a)
        print(res)

    # region fastio
BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
def input(): return sys.stdin.readline().rstrip("\r\n")

# endregion

if __name__ == "__main__":
    main()


#!/usr/bin/env python
import os
import re
import sys
from bisect import bisect, bisect_left, insort, insort_left
from collections import Counter, defaultdict, deque
from copy import deepcopy
from decimal import Decimal
from fractions import gcd
from io import BytesIO, IOBase
from itertools import (
    accumulate, combinations, combinations_with_replacement, groupby,
    permutations, product)
from math import (
    acos, asin, atan, ceil, cos, degrees, factorial, hypot, log2, pi, radians,
    sin, sqrt, tan)
from operator import itemgetter, mul
from string import ascii_lowercase, ascii_uppercase, digits

def inp():
    return(int(input()))

def inlist():
    return(list(map(int, input().split())))

def instr():
    s = input()
    return(list(s[:len(s)]))

def invr():
    return(map(int, input().split()))

def isValid(k, a):
    n = len(a)
    for i in range(0, n-k+1):
        temp = a[i:i+k]
        # print(temp)
        count = defaultdict(lambda: 0)
        for c in temp:
            count[c] += 1
        if count['1'] > 0 and count['2'] > 0 and count['3'] > 0:
            return True
    return False

def b_serach(a):
    l = 3
    r = len(a)
    ans = 0
    while l <= r:
        mid = l + (r - l) // 2
        if isValid(mid, a):
            ans = mid
            r = mid - 1
        else:
            l = mid + 1
    return ans

def main():
    # sys.stdin = open('input.txt', 'r')
    # sys.stdout = open('output.txt', 'w')

    t = inp()
    for _ in range(t):
        a = input()
        res = b_serach(a)
        print(res)

    # region fastio
BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
def input(): return sys.stdin.readline().rstrip("\r\n")

# endregion

if __name__ == "__main__":
    main()


#!/usr/bin/env python
import os
import re
import sys
from bisect import bisect, bisect_left, insort, insort_left
from collections import Counter, defaultdict, deque
from copy import deepcopy
from decimal import Decimal
from fractions import gcd
from io import BytesIO, IOBase
from itertools import (
    accumulate, combinations, combinations_with_replacement, groupby,
    permutations, product)
from math import (
    acos, asin, atan, ceil, cos, degrees, factorial, hypot, log2, pi, radians,
    sin, sqrt, tan)
from operator import itemgetter, mul
from string import ascii_lowercase, ascii_uppercase, digits

def inp():
    return(int(input()))

def inlist():
    return(list(map(int, input().split())))

def instr():
    s = input()
    return(list(s[:len(s)]))

def invr():
    return(map(int, input().split()))

def isValid(k, a):
    n = len(a)
    for i in range(0, n-k+1):
        count = defaultdict(lambda: 0)
        for j in range(i, i + k):
            count[a[j]] += 1
        if count['1'] > 0 and count['2'] > 0 and count['3'] > 0:
            return True
    return False

def b_serach(a):
    l = 3
    r = len(a)
    ans = 0
    while l <= r:
        mid = l + (r - l) // 2
        if isValid(mid, a):
            ans = mid
            r = mid - 1
        else:
            l = mid + 1
    return ans

def main():
    # sys.stdin = open('input.txt', 'r')
    # sys.stdout = open('output.txt', 'w')

    t = inp()
    for _ in range(t):
        a = input()
        res = b_serach(a)
        print(res)

    # region fastio
BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
def input(): return sys.stdin.readline().rstrip("\r\n")

# endregion

if __name__ == "__main__":
    main()


import sys
input = sys.stdin.readline

def isvalid(c):
    i = 0
    f = 0
    l = [-1]*4
    while i < len(s)-1:
        x = s[i]
        if x == "1":
            l[1] = i

        if x == "2":
            l[2] = i

        if x == "3":
            l[3] = i

        if l[1] != -1 and l[2] != -1 and l[3] != -1:
            e = max(l[1], l[2], l[3])
            y = min(l[1], l[2], l[3])
            z = e - y + 1
            if z <= c:
                f = 1

        i += 1

    return f

for _ in range(int(input())):
    s = input()
    high = 200001
    low = 0
    while low < high:
        mid = (low+high)//2
        r = isvalid(mid)
        if r == 1:
            high = mid

        else:
            low = mid+1

    if high == 200001:
        print(0)

    else:
        print(high)


def isvalid(c):
    i = 0
    f = 0
    l = [-1]*4
    while i < len(s):
        x = s[i]
        if x == "1":
            l[1] = i

        if x == "2":
            l[2] = i

        if x == "3":
            l[3] = i

        if l[1] != -1 and l[2] != -1 and l[3] != -1:
            e = max(l[1], l[2], l[3])
            y = min(l[1], l[2], l[3])
            z = e - y + 1
            if z <= c:
                f = 1

        i += 1

    return f

for _ in range(int(input())):
    s = input()
    high = 200001
    low = 0
    while low < high:
        mid = (low+high)//2
        r = isvalid(mid)
        if r == 1:
            high = mid

        else:
            low = mid+1

    if high == 200001:
        print(0)

    else:
        print(high)


import sys
input = sys.stdin.readline

def isvalid(c):
    i = 0
    f = 0
    l = [-1]*4
    while i < len(s)-1:
        x = s[i]
        if x == "1":
            l[1] = i

        if x == "2":
            l[2] = i

        if x == "3":
            l[3] = i

        if l[1] != -1 and l[2] != -1 and l[3] != -1:
            e = max(l[1], l[2], l[3])
            y = min(l[1], l[2], l[3])
            z = e - y + 1
            if z <= c:
                f = 1
                break

        i += 1

    return f

for _ in range(int(input())):
    s = input()
    high = 200001
    low = 0
    while low < high:
        mid = (low+high)//2
        r = isvalid(mid)
        if r == 1:
            high = mid

        else:
            low = mid+1

    if high == 200001:
        print(0)

    else:
        print(high)


#!/usr/bin/env python
from __future__ import division, print_function

import os
import sys
from io import BytesIO, IOBase
import datetime

if sys.version_info[0] < 3:
    from __builtin__ import xrange as range
    from future_builtins import ascii, filter, hex, map, oct, zip

def main():
    starttime=datetime.datetime.now()
    #ifndef ONLINE_JUDGE
    # sys.stdin=open('input.txt','r')
    # sys.stdout=open('output.txt','w')
    #endif
    for _ in range(int(input())):
        s=input()
        z=len(s)
        l=0
        r=0
        k=0
        m=99999999999999
        for i in range(z-1):
            if s[i]!=s[i+1]:
                l=i
                k=ord(s[i])+ord(s[i+1])
                break
        for i in range(l+1,z-1):
            if s[i]!=s[i+1]:
                if ord(s[i])+ord(s[i+1])==k:
                    l=i
                else:
                    r=i
                    m=min(r-l+2,m)
                    k=ord(s[i])+ord(s[i+1])
        if m==99999999999999:
            print(0)
        else:
            print(m)

    endtime=datetime.datetime.now()
    time=(endtime-starttime).total_seconds()*1000
    # print("Time:",time,"ms")

# region fastio

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

def print(*args, **kwargs):
    """Prints the values to a stream, or to sys.stdout by default."""
    sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
    at_start = True
    for x in args:
        if not at_start:
            file.write(sep)
        file.write(str(x))
        at_start = False
    file.write(kwargs.pop("end", "\n"))
    if kwargs.pop("flush", False):
        file.flush()

if sys.version_info[0] < 3:
    sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
    sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)

input = lambda: sys.stdin.readline().rstrip("\r\n")

# endregion

if __name__ == "__main__":
    main()


#!/usr/bin/env python
from __future__ import division, print_function

import os
import sys
from io import BytesIO, IOBase
import datetime

if sys.version_info[0] < 3:
    from __builtin__ import xrange as range
    from future_builtins import ascii, filter, hex, map, oct, zip

def main():
    starttime=datetime.datetime.now()
    #ifndef ONLINE_JUDGE
    sys.stdin=open('input.txt','r')
    sys.stdout=open('output.txt','w')
    #endif
    for _ in range(int(input())):
        s=input()
        z=len(s)
        l=0
        r=0
        k=0
        m=99999999999999
        for i in range(z-1):
            if s[i]!=s[i+1]:
                l=i
                k=ord(s[i])+ord(s[i+1])
                break
        for i in range(l+1,z-1):
            if s[i]!=s[i+1]:
                if ord(s[i])+ord(s[i+1])==k:
                    l=i
                else:
                    r=i
                    m=min(r-l+2,m)
                    k=ord(s[i])+ord(s[i+1])
                    l=i
        if m==99999999999999:
            print(0)
        else:
            print(m)

    endtime=datetime.datetime.now()
    time=(endtime-starttime).total_seconds()*1000
    # print("Time:",time,"ms")

# region fastio

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

def print(*args, **kwargs):
    """Prints the values to a stream, or to sys.stdout by default."""
    sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
    at_start = True
    for x in args:
        if not at_start:
            file.write(sep)
        file.write(str(x))
        at_start = False
    file.write(kwargs.pop("end", "\n"))
    if kwargs.pop("flush", False):
        file.flush()

if sys.version_info[0] < 3:
    sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
    sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)

input = lambda: sys.stdin.readline().rstrip("\r\n")

# endregion

if __name__ == "__main__":
    main()