You are given a string $s$ such that each its character is either 1, 2, or 3. You have to choose the shortest contiguous substring of $s$ such that it contains each of these three characters at least once.

A contiguous substring of string $s$ is a string that can be obtained from $s$ by removing some (possibly zero) characters from the beginning of $s$ and some (possibly zero) characters from the end of $s$.


-----Input-----

The first line contains one integer $t$ ($1 \le t \le 20000$) — the number of test cases.

Each test case consists of one line containing the string $s$ ($1 \le |s| \le 200000$). It is guaranteed that each character of $s$ is either 1, 2, or 3.

The sum of lengths of all strings in all test cases does not exceed $200000$.


-----Output-----

For each test case, print one integer — the length of the shortest contiguous substring of $s$ containing all three types of characters at least once. If there is no such substring, print $0$ instead.


-----Example-----
Input
7
123
12222133333332
112233
332211
12121212
333333
31121

Output
3
3
4
4
0
0
4



-----Note-----

Consider the example test:

In the first test case, the substring 123 can be used.

In the second test case, the substring 213 can be used.

In the third test case, the substring 1223 can be used.

In the fourth test case, the substring 3221 can be used.

In the fifth test case, there is no character 3 in $s$.

In the sixth test case, there is no character 1 in $s$.

In the seventh test case, the substring 3112 can be used.

Difficulty: EASY
Tags: Dynamic programming

Sorting

Amortized analysis

Implementation
Skill types: Dynamic programming

Sorting

Amortized analysis

Starter code:

Solutions:
def tstring(s):
	counts = [s.count('1'), s.count('2'), s.count('3')]
	if 0 in counts:
		return 0
	minlen = len(s)
	recent = [None, None, None]
	for i in range(len(s)):
		n = int(s[i]) - 1
		recent[n] = i
		if None in recent:
			continue
		l = min(recent)
		minlen = min(minlen, i - l + 1)
	return minlen
n = int(input())
ll = []
for i in range(n):
	s = input()
	ll.append(s)
for s in ll:
	print(tstring(s))


def solve(s):
	p = 0
	h = 0
	ans = 2000000
	acc = False
	counter = [0, 0, 0]
	nums = list(map(lambda x: int(x) - 1, s))
	while p < len(s):
		counter[nums[p]] += 1
		if not acc and counter[0] >= 1 and (counter[1] >= 1) and (counter[2] >= 1):
			acc = True
		while counter[nums[h]] > 1:
			counter[nums[h]] -= 1
			h += 1
		if acc:
			ans = min(ans, p - h + 1)
		p += 1
	if ans == 2000000:
		ans = 0
	return ans

def main():
	T = int(input())
	for i in range(1, T + 1):
		s = input().strip()
		print(solve(s))
main()


from collections import defaultdict as dd
I = input
for _ in range(int(I())):
	s = I()
	d = dd(int)
	for i in '123':
		d[i] = -1
	l = 10 ** 18
	for i in range(len(s)):
		d[s[i]] = i
		mn = min(*d.values())
		mx = max(*d.values())
		if mn != -1:
			l = min(l, mx - mn + 1)
	if l != 10 ** 18:
		print(l)
	else:
		print(0)


import sys
import collections
import math
import functools
import itertools
import bisect
import operator
import heapq
import random
true = True
false = False
null = None
tcid = 0
tcmax = 99999999

def compute(val, func):
	return func(val)

def seq(lo, hi, step=1):
	return range(lo, hi + 1, step)

def sround(val, nd):
	return f'{val:.{nd}f}'

def ceil(a, b):
	ans = a // b
	if a % b != 0:
		ans += 1
	return ans

def perr(*args, **kwargs):
	print(*args, file=sys.stderr, **kwargs)

def line():
	ln = sys.stdin.readline().strip()
	if ln == '':
		sys.exit()
	return ln

def lines(n):
	return [line() for i in range(n)]

def split(ln=None):
	return (ln or line()).split()

def num(str=None):
	str = str or line()
	return float(str) if '.' in str else int(str)

def nums(o=None):
	if o is not None:
		if isinstance(o, int):
			o = lines(o)
		elif isinstance(o, str):
			o = split(o)
	return list(map(num, o or split()))
tcmax = num()

def mainloop(tcid=1):
	s = []
	for cc in line():
		s.append(int(cc))
	big = 999999
	ans = big
	a0 = [-1] * 3
	for ii in range(len(s)):
		a0[s[ii] - 1] = ii
		jj = min(a0)
		if jj > -1:
			ans = min(ans, ii - jj + 1)
	if ans == big:
		ans = 0
	print(ans)
while tcid < tcmax:
	tcid += 1
	mainloop(tcid)


from collections import deque
t = int(input())
for _ in range(t):
	s = input()
	i = 0
	j = 0
	idxs = [deque(), deque(), deque()]
	cur_min = -1
	while j <= len(s):
		if len(idxs[0]) > 0 and len(idxs[1]) > 0 and (len(idxs[2]) > 0):
			last_j = j - k
			(l, r) = idxs[int(s[i]) - 1].popleft()
			if cur_min == -1:
				cur_min = last_j - r
			else:
				cur_min = min(cur_min, last_j - r)
			i = r + 1
			if i >= len(s) or j >= len(s):
				break
		if j == len(s):
			break
		if s[i] == s[j] and j != 0:
			(l, r) = idxs[int(s[j]) - 1].popleft()
			i = r + 1
		k = 0
		while j + k < len(s) and s[j] == s[j + k]:
			k += 1
		idxs[int(s[j]) - 1].append((j, j + k - 1))
		j += k
	print(cur_min + 1)


t = int(input())
for i in range(t):
	qw = input()
	s = set(qw)
	if len(s) != 3:
		print(0)
	else:
		(x, y, z, n) = (0, 0, 0, len(qw))
		for i in range(len(qw)):
			if qw[i] == '1':
				x = i + 1
			if qw[i] == '2':
				y = i + 1
			if qw[i] == '3':
				z = i + 1
			if x > 0 and y > 0 and (z > 0):
				(p, q) = (max(x, y, z), min(x, y, z))
				n = min(n, p - q + 1)
		print(n)


from sys import stdin
for t in range(int(stdin.readline())):
	s = input()
	a = []
	b = []
	c = []
	n = len(s)
	for i in range(n):
		if s[i] == '1':
			a.append(i)
		elif s[i] == '2':
			b.append(i)
		else:
			c.append(i)
	a.reverse()
	b.reverse()
	c.reverse()
	if a == [] or b == [] or c == []:
		print(0)
		continue
	mi = 10 ** 6
	l = 0
	for i in range(n):
		flag = 0
		if s[i] == '1':
			while b[-1] < i:
				b.pop()
				if b == []:
					flag = 1
					break
			if flag == 1:
				break
			while c[-1] < i:
				c.pop()
				if c == []:
					flag = 1
					break
			if flag == 1:
				break
			m = max(b[-1], c[-1])
			l = m - i + 1
		elif s[i] == '2':
			while a[-1] < i:
				a.pop()
				if a == []:
					flag = 1
					break
			if flag == 1:
				break
			while c[-1] < i:
				c.pop()
				if c == []:
					flag = 1
					break
			if flag == 1:
				break
			m = max(a[-1], c[-1])
			l = m - i + 1
		else:
			while a[-1] < i:
				a.pop()
				if a == []:
					flag = 1
					break
			if flag == 1:
				break
			while b[-1] < i:
				b.pop()
				if b == []:
					flag = 1
					break
			if flag == 1:
				break
			m = max(a[-1], b[-1])
			l = m - i + 1
		if mi > l:
			mi = l
			if mi == 3:
				break
	print(mi)


from collections import defaultdict
for i in range(int(input())):
	x = input()
	cnt = len(set([i for i in x]))
	current = defaultdict(lambda : 0)
	c = 0
	mn = len(x)
	s = 0
	for j in range(len(x)):
		current[x[j]] += 1
		if current[x[j]] == 1:
			c += 1
		if c == cnt:
			while current[x[s]] > 1:
				if current[x[s]] > 1:
					current[x[s]] -= 1
				s += 1
			w = j - s + 1
			if mn > w:
				mn = w
	if mn < 3:
		print(0)
	else:
		print(mn)


import sys
import heapq

def main():
	t = int(input())
	for _ in range(t):
		s = sys.stdin.readline().strip()
		pos1 = None
		pos2 = None
		pos3 = None
		ans = len(s)
		for i in range(len(s)):
			if s[i] == '1':
				pos1 = i
			elif s[i] == '2':
				pos2 = i
			else:
				pos3 = i
			if not (pos1 == None or pos2 == None or pos3 == None):
				ans = min(ans, max(pos1, pos2, pos3) - min(pos1, pos2, pos3) + 1)
		if pos1 == None or pos2 == None or pos3 == None:
			print(0)
		else:
			print(ans)
	return
main()


import sys
max_int = 1000000001
min_int = -max_int
t = int(input())
for _t in range(t):
	s = sys.stdin.readline()[:-1]
	out = []
	prev_s = s[0]
	cnt = 0
	prev_letter = False
	for i in range(len(s)):
		if s[i] == prev_s:
			cnt += 1
			continue
		if prev_letter and prev_letter != s[i]:
			out.append(cnt)
		prev_letter = prev_s
		prev_s = s[i]
		cnt = 1
	print(min(out) + 2 if out else 0)


for _ in range(int(input())):
	st = input()
	se = 1
	ans = 1
	tem = st[0]
	li = []
	flag = False
	for i in range(1, len(st)):
		if tem[0] == st[i]:
			if ans != 1:
				ans = 2
				tem = tem[-1] + st[i]
		else:
			tem += st[i]
			ans += 1
			if tem[-1] != tem[-2]:
				se += 1
		if se == 3:
			flag = True
			li.append(ans)
			ans = 2
			tem = tem[1] + tem[-1]
			se = 2
	if flag:
		print(min(li))
	else:
		print(0)


from sys import stdin, stdout

def sub_cnt(s):
	n = len(s)
	if n < 3:
		return 0
	cnts = [0] * (n + 1)
	(start, start_index, min_len) = (0, -1, float('inf'))
	count = 0
	for j in range(n):
		cnts[s[j]] += 1
		if cnts[s[j]] <= 1:
			count += 1
		if count >= 3:
			while cnts[s[start]] > 1:
				if cnts[s[start]] > 1:
					cnts[s[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 0
	return min_len
for _ in range(int(stdin.readline())):
	s = list(map(int, list(stdin.readline())[:-1]))
	stdout.write(str(sub_cnt(s)) + '\n')


import sys
t = int(input())
for _ in range(t):
	s = input()
	(pos1, pos2, pos3, ans) = (-1, -1, -1, sys.maxsize)
	for i in range(len(s)):
		if s[i] == '1':
			pos1 = i
		if s[i] == '2':
			pos2 = i
		if s[i] == '3':
			pos3 = i
		if pos1 != -1 and pos2 != -1 and (pos3 != -1):
			ans = min(ans, max(pos1, pos2, pos3) - min(pos1, pos2, pos3) + 1)
	if ans == sys.maxsize:
		print(0)
	else:
		print(ans)


arr = []
for _ in range(int(input())):
	del arr[:]
	s = input() + '.'
	curr = 1
	one = False
	two = False
	three = False
	for i in range(len(s) - 1):
		if s[i] == '1':
			one = True
		if s[i] == '2':
			two = True
		if s[i] == '3':
			three = True
		if s[i] == s[i + 1]:
			curr += 1
		else:
			arr.append((s[i], curr))
			curr = 1
	if not (one and two and three):
		print(0)
		continue
	best = float('inf')
	for i in range(len(arr) - 2):
		if arr[i][0] != arr[i + 1][0] and arr[i + 1][0] != arr[i + 2][0] and (arr[i + 2][0] != arr[i][0]):
			best = min(best, arr[i + 1][1] + 2)
	print(best)


import sys
input = sys.stdin.readline

def solve(s):
	L = []
	if '1' not in s or '2' not in s or '3' not in s:
		return 0
	for i in range(len(s)):
		if len(L) == 0 or L[-1][-1] != s[i]:
			L.append([1, s[i]])
		else:
			L[-1][0] += 1
	min = 9999999999
	for i in range(len(L) - 2):
		(L1, L2, L3) = (L[i], L[i + 1], L[i + 2])
		LL = [L1[1], L2[1], L3[1]]
		if '1' in LL and '2' in LL and ('3' in LL):
			mm = L2[0] + 2
			if mm < min:
				min = mm
	return min
for i in ' ' * int(input()):
	print(solve(input().strip('\n')))


def answer(s):
	if len(set(s)) < 3:
		return 0
	A = [0, 0, 0]
	l = 0
	r = 0
	mini = 2147483647
	while r < len(s):
		if A[0] > 0 and A[1] > 0 and (A[2] > 0):
			mini = min(mini, r - l)
			if s[l] == '1':
				A[0] -= 1
			elif s[l] == '2':
				A[1] -= 1
			elif s[l] == '3':
				A[2] -= 1
			l += 1
		else:
			if s[r] == '1':
				A[0] += 1
			elif s[r] == '2':
				A[1] += 1
			elif s[r] == '3':
				A[2] += 1
			r += 1
	if A[0] > 0 and A[1] > 0 and (A[2] > 0):
		while r > l:
			if A[0] > 0 and A[1] > 0 and (A[2] > 0):
				mini = min(mini, r - l)
				if s[l] == '1':
					A[0] -= 1
				elif s[l] == '2':
					A[1] -= 1
				elif s[l] == '3':
					A[2] -= 1
				l += 1
			else:
				break
	return mini
t = int(input())
for i in range(t):
	a = input()
	print(answer(a))


from collections import defaultdict
import math
MAX_CHARS = 256

def findSubString(str):
	n = len(str)
	dist_count = len(set([x for x in str]))
	curr_count = defaultdict(lambda : 0)
	count = 0
	start = 0
	min_len = float('inf')
	for j in range(n):
		curr_count[str[j]] += 1
		if curr_count[str[j]] == 1:
			count += 1
		if count == dist_count:
			while curr_count[str[start]] > 1:
				if curr_count[str[start]] > 1:
					curr_count[str[start]] -= 1
				start += 1
			len_window = j - start + 1
			if min_len > len_window:
				min_len = len_window
				start_index = start
	return str[start_index:start_index + min_len]
t = int(input())
for _ in range(t):
	s = input()
	if '1' in s and '2' in s and ('3' in s):
		ans = len(findSubString(s))
	else:
		ans = 0
	print(ans)


t = int(input())
for i in range(t):
	s = str(input())
	len1 = len(s)
	lis = [-1, -1, -1]
	ans = 0
	for j in range(len1):
		if s[j] == '1':
			lis[0] = j
		if s[j] == '2':
			lis[1] = j
		if s[j] == '3':
			lis[2] = j
		min1 = min(lis)
		if min1 != -1:
			max1 = max(lis)
			if ans == 0:
				ans = max1 - min1 + 1
			else:
				ans = min(ans, max1 - min1 + 1)
	print(ans)


def solution():
	s = input()
	mi = 200001
	for i in range(1, len(s)):
		if s[i] != s[i - 1]:
			f = i
			n = 1
			t = s[i - 1]
			break
	else:
		return 0
	for i in range(f + 1, len(s)):
		if s[i] != s[i - 1]:
			if t != s[i]:
				mi = min(n + 2, mi)
				n = 1
				t = s[i - 1]
				if mi == 3:
					break
			else:
				t = s[i - 1]
				n = 1
		else:
			n += 1
	if mi == 200001:
		return 0
	else:
		return mi
for _ in range(int(input())):
	print(solution())


t = int(input())
for _ in range(t):
	n = input()
	(i, j) = (0, 1)
	minLen = float('inf')
	while j < len(n) - 1:
		if n[i] != n[j] != n[j + 1] != n[i]:
			minLen = min(minLen, j + 1 - i + 1)
			i = j
		elif n[j + 1] == n[i] or n[j] == n[i]:
			i = j
		j += 1
	print(minLen if minLen != float('inf') else 0)


for _ in range(int(input())):
	s = input()
	found = {}
	i = 0
	while len(found) < 3 and i < len(s):
		if s[i] in found:
			found[s[i]] += 1
		else:
			found[s[i]] = 1
		i += 1
	if len(found) < 3:
		print(0)
		continue
	j = i
	i = 0
	while True:
		while len(found) == 3:
			found[s[i]] -= 1
			if found[s[i]] == 0:
				del found[s[i]]
			i += 1
		if j == len(s):
			break
		if s[j] in found:
			found[s[j]] += 1
		else:
			found[s[j]] = 1
		j += 1
		found[s[i]] -= 1
		if found[s[i]] == 0:
			del found[s[i]]
		i += 1
	print(j - i + 1)


Q = int(input())
list = []
while Q > 0:
	Q -= 1
	string = input()
	nr1 = nr2 = nr3 = 0
	min = 1000000
	start = 0
	crt = -1
	for i in string:
		crt += 1
		if i == '1':
			nr1 += 1
		if i == '2':
			nr2 += 1
		if i == '3':
			nr3 += 1
		while nr1 > (string[start] == '1') and nr2 > (string[start] == '2') and (nr3 > (string[start] == '3')):
			nr1 -= string[start] == '1'
			nr2 -= string[start] == '2'
			nr3 -= string[start] == '3'
			start += 1
		if nr1 >= 1 and nr2 >= 1 and (nr3 >= 1) and (min > crt - start + 1):
			min = crt - start + 1
	if min == 1000000:
		min = 0
	list.append(str(min))
for i in list:
	print(i)


from sys import stdin, stdout
for test in range(int(stdin.readline())):
	inp = stdin.readline()
	ind1 = -1
	ind2 = -1
	ind3 = -1
	count = 200001
	for i in range(len(inp)):
		if inp[i] == '1':
			ind1 = i
		elif inp[i] == '2':
			ind2 = i
		elif inp[i] == '3':
			ind3 = i
		else:
			pass
		if ind1 != -1 and ind2 != -1 and (ind3 != -1):
			t = max(ind1, ind2, ind3) + 1 - min(ind1, ind2, ind3)
			if t <= count:
				count = t
	if count == 200001:
		stdout.write('0\n')
	else:
		stdout.write(str(count) + '\n')


n = int(input())
for rr in range(0, n):
	a = input()
	b = [0, 0, 0]
	i = 0
	while not (b[0] > 0 and b[1] > 0 and (b[2] > 0)) and len(a) > i:
		b[int(a[i]) - 1] += 1
		i += 1
	q = 0
	while b[0] > 0 and b[1] > 0 and (b[2] > 0) and (i > q):
		b[int(a[q]) - 1] -= 1
		q += 1
	b[int(a[q - 1]) - 1] += 1
	if i == len(a) and (not (b[0] > 0 and b[1] > 0 and (b[2] > 0))):
		print(0)
	else:
		s = i - q + 1
		q -= 1
		for j in range(i, len(a)):
			b[int(a[j]) - 1] += 1
			while b[0] > 0 and b[1] > 0 and (b[2] > 0) and (j > q):
				b[int(a[q]) - 1] -= 1
				q += 1
			b[int(a[q - 1]) - 1] += 1
			q -= 1
			s = min(s, j - q + 1)
		print(s)


def find_shortest_substr(s):
	dist_chars = ('1', '2', '3')
	found_chars = dict()
	start = 0
	len_min = len(s)
	distinct_char_count = 0
	start_index = 0
	for (i, c) in enumerate(s):
		found_chars[c] = found_chars.get(c, 0) + 1
		if found_chars[c] == 1:
			distinct_char_count += 1
		if distinct_char_count == 3:
			while found_chars[s[start]] > 1:
				found_chars[s[start]] -= 1
				start += 1
			len_window = i + 1 - start
			if len_window < len_min:
				len_min = len_window
				start_index = start
	if distinct_char_count < 3:
		return 0
	else:
		return len_min
for _ in range(int(input())):
	print(find_shortest_substr(input()))


R1 = lambda : list(map(int, input().split()))
R2 = lambda : int(input())
for _ in range(R2()):
	A = input()
	d = [-1] * 3
	res = 1000000000.0
	for i in range(len(A)):
		d[int(A[i]) - 1] = i
		if -1 not in d:
			res = min(res, max(d) - min(d) + 1)
	if res == 1000000000.0:
		print(0)
	else:
		print(res)


t = int(input())
for i in range(t):
	S = input()
	if len(set(list(S))) != 3:
		print(0)
	else:
		ans = len(S)
		firstNums = [-1] * 3
		firstNums[int(S[0]) - 1] = 0
		for i in range(len(S) - 1):
			if S[i] != S[i + 1]:
				firstNums[int(S[i]) - 1] = i
				firstNums[int(S[i + 1]) - 1] = i + 1
				if firstNums[0] != -1 and firstNums[1] != -1 and (firstNums[2] != -1):
					ans = min(ans, max(firstNums) - min(firstNums) + 1)
		print(ans)


for i in range(int(input())):
	s = str(input())
	if len(set(s)) <= 2:
		print(0)
	else:
		lv = []
		lk = []
		co = 1
		for i in range(len(s) - 1):
			if s[i] != s[i + 1]:
				lk.append(s[i])
				lv.append(co)
				co = 1
			else:
				co += 1
			if i == len(s) - 2:
				lk.append(s[i + 1])
				lv.append(co)
				co = 1
		mino = 10 ** 10
		for i in range(len(lv) - 2):
			if lk[i] != lk[i + 1] and lk[i + 1] != lk[i + 2] and (lk[i] != lk[i + 2]):
				mino = min(mino, lv[i + 1])
		print(mino + 2)


def rez():
	s = input()
	one = 100000000
	two = 100000000
	thee = 1000000000
	ans = len(s)
	for i in range(len(s)):
		if s[i] == '1':
			one = i
		elif s[i] == '2':
			two = i
		else:
			thee = i
		if max(one, two, thee) - min(one, two, thee) < ans:
			ans = max(one, two, thee) - min(one, two, thee)
	if max(one, two, thee) <= len(s):
		print(ans + 1)
	else:
		print(0)
for t in range(int(input())):
	rez()


class SegmentTree:

	def __init__(self, data, default=0, func=lambda a, b: gcd(a, b)):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)
import os
import sys
from io import BytesIO, IOBase
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))
input = lambda : sys.stdin.readline().rstrip('\r\n')
from bisect import bisect_right, bisect_left
from fractions import Fraction

def pre(s):
	n = len(s)
	pi = [0] * n
	for i in range(1, n):
		j = pi[i - 1]
		while j and s[i] != s[j]:
			j = pi[j - 1]
		if s[i] == s[j]:
			j += 1
		pi[i] = j
	return pi

def prod(a):
	ans = 1
	for each in a:
		ans = ans * each
	return ans
from math import gcd

def lcm(a, b):
	return a * b // gcd(a, b)

def binary(x, length=16):
	y = bin(x)[2:]
	return y if len(y) >= length else '0' * (length - len(y)) + y

def pt(x, y):
	return str(x) + ',' + str(y)
for _ in range(int(input()) if True else 1):
	s = input()
	(x, y, z) = (False, False, False)
	for i in s:
		if i == '1':
			x = True
		if i == '2':
			y = True
		if i == '3':
			z = True
	if not x or not y or (not z):
		print(0)
		continue
	x = []
	y = []
	z = []
	for i in range(len(s)):
		if s[i] == '1':
			x += [i]
		elif s[i] == '2':
			y += [i]
		elif s[i] == '3':
			z += [i]
	ans = len(s)
	for x1 in x:
		x2 = bisect_right(y, x1)
		x3 = bisect_right(z, x1)
		(x2c, x3c) = (x2, x3)
		if x2 != len(y) and x3 != len(z):
			x2 = y[x2]
			x3 = z[x3]
			ans = min(ans, max(x2, x3) - x1 + 1)
		x4 = bisect_left(y, x1) - 1
		x5 = bisect_left(z, x1) - 1
		(x4c, x5c) = (x4, x5)
		if x4 != -1 and x5 != -1:
			x4 = y[x4]
			x5 = z[x5]
			ans = min(ans, x1 - min(x4, x5) + 1)
		(x2, x3, x4, x5) = (x2c, x3c, x4c, x5c)
		if x4 != -1 and x3 != len(z):
			x44 = y[x4]
			x33 = z[x3]
			ans = min(ans, x33 - x44 + 1)
		if x5 != -1 and x2 != len(y):
			x2 = y[x2]
			x5 = z[x5]
			ans = min(ans, x2 - x5 + 1)
	print(ans)


from sys import stdin, stdout
from collections import Counter
from itertools import permutations
import bisect
import math
I = lambda : map(int, stdin.readline().split())
I1 = lambda : stdin.readline()
for _ in range(int(I1())):
	s = I1().strip()
	i = 1
	a = []
	n = len(s)
	c = 0
	while i < n:
		if s[i] == s[i - 1]:
			c += 1
		else:
			a.append(list([s[i - 1], c + 1]))
			c = 0
		i += 1
	a.append(list([s[i - 1], c + 1]))
	l = len(a)
	i = 0
	m = 2000000
	while i < l - 2:
		if a[i][0] != a[i + 1][0] and a[i + 1][0] != a[i + 2][0] and (a[i][0] != a[i + 2][0]):
			m = min(m, 2 + a[i + 1][1])
		i += 1
	if m == 2000000:
		print(0)
	else:
		print(m)


import math
from collections import defaultdict as dd
from bisect import bisect as b
import sys
input = sys.stdin.readline
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)


def parse():
	return list(map(int, list(input())))

def calc(s):
	s1 = []
	prev = 0
	for c in s:
		if prev == c:
			t = s1[len(s1) - 1]
			s1[len(s1) - 1] = (c, t[1] + 1)
		else:
			s1.append((c, 1))
		prev = c
	minmax = 999999999999999
	min = minmax
	for j in range(0, len(s1)):
		try:
			x = s1[j]
			y = s1[j + 1]
			z = s1[j + 2]
			if y[0] != x[0] and z[0] != x[0]:
				sum = 1 + y[1] + 1
				min = sum if sum < min else min
		except IndexError:
			continue
	return min if minmax != min else 0
t = int(input())
for i in range(0, t):
	print(calc(parse()))


import sys
from functools import lru_cache, cmp_to_key
from heapq import merge, heapify, heappop, heappush
from math import ceil, floor, gcd, fabs, factorial, fmod, sqrt, inf, log
from collections import defaultdict as dd, deque, Counter as C
from itertools import combinations as comb, permutations as perm
from bisect import bisect_left as bl, bisect_right as br, bisect
from time import perf_counter
from fractions import Fraction
mod = pow(10, 9) + 7
mod2 = 998244353

def data():
	return sys.stdin.readline().strip()

def out(*var, end='\n'):
	sys.stdout.write(' '.join(map(str, var)) + end)

def l():
	return list(sp())

def sl():
	return list(ssp())

def sp():
	return map(int, data().split())

def ssp():
	return map(str, data().split())

def l1d(n, val=0):
	return [val for i in range(n)]

def l2d(n, m, val=0):
	return [l1d(n, val) for j in range(m)]
for _ in range(int(data())):
	s = data()
	if '1' not in s or '2' not in s or '3' not in s:
		out(0)
		continue
	(a, b, c) = (-1, -1, -1)
	answer = inf
	for i in range(len(s)):
		if s[i] == '1':
			a = i
		elif s[i] == '2':
			b = i
		else:
			c = i
		if a != -1 and b != -1 and (c != -1):
			answer = min(answer, max(a, b, c) - min(a, b, c) + 1)
	out(answer)


import sys
_INPUT_LINES = sys.stdin.read().splitlines()
input = iter(_INPUT_LINES).__next__
from itertools import islice, cycle

def go():
	s = input()
	last = {}
	best = len(s) + 4
	for (i, ss) in enumerate(s):
		last[ss] = i
		if len(last) == 3:
			best = min(best, 1 + max(last.values()) - min(last.values()))
	if best <= len(s):
		return best
	else:
		return 0
t = int(input())
ans = []
for _ in range(t):
	ans.append(str(go()))
print('\n'.join(ans))


def style(s, st, a):
	mid = '0'
	ind = -1
	if len(s) == 1 or 3 in a:
		return
	for i in range(1, len(s)):
		if s[i] != st:
			mid = s[i]
			ind = i
			break
	end = ['1', '2', '3']
	end.remove(st)
	end.remove(mid)
	end = end[0]
	if ind != -1:
		i = ind + 1
		while i < len(s):
			if s[i] == end:
				l = i - ind + 2
				a.append(l)
				style(s[i - 1:], s[i - 1], a)
				break
			elif s[i] != s[i - 1]:
				ind = i
			i += 1
	return a
from collections import Counter
for _ in range(int(input())):
	s = input()
	a = []
	if '1' not in s or '2' not in s or '3' not in s:
		print(0)
	else:
		style(s, s[0], a)
		a.sort()
		print(a[0])


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

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

def inputArray():
	return input().rstrip().split()

def inputVars():
	return map(int, input().rstrip().split())

def inputNum():
	return int(input())

def main():
	for _ in range(inputNum()):
		text = input()
		if len(text) < 3:
			print(0)
			continue
		leftPointer = 0
		rightPointer = 2
		freqHash = collections.Counter(text[0:3])
		toMatchHash = collections.Counter('123')
		length = len(text)
		minLength = float('inf')
		flag = False
		while leftPointer < length and rightPointer < length:
			if not toMatchHash - freqHash:
				flag = True
				minLength = min(minLength, rightPointer - leftPointer + 1)
				leftPointer += 1
				freqHash[text[leftPointer - 1]] -= 1
			else:
				rightPointer += 1
				if rightPointer >= length:
					break
				freqHash[text[rightPointer]] += 1
		if flag:
			print(minLength)
		else:
			print(0)
main()
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))
input = lambda : sys.stdin.readline().rstrip('\r\n')


import math
for _ in range(int(input())):
	s = list(map(int, input()))
	ar = [-1, -1, -1]
	p = 100000000
	x = 0
	for i in range(len(s)):
		if s[i] == 1:
			ar[0] = max(ar[0], i)
		elif s[i] == 2:
			ar[1] = max(ar[1], i)
		elif s[i] == 3:
			ar[2] = max(ar[2], i)
		if ar[0] >= 0 and ar[1] >= 0 and (ar[2] >= 0):
			p = min(p, max(ar) - min(ar))
	if p > 200000:
		print(0)
	else:
		print(p + 1)


from sys import stdin
import math
t = int(stdin.readline())
for _ in range(t):
	s = input()
	if set(s) != {'1', '2', '3'}:
		print(0)
		continue
	i1 = 0
	i2 = 0
	i3 = 0
	for i in range(len(s)):
		if s[i] == '1':
			i1 = i
	for i in range(len(s)):
		if s[i] == '2':
			i2 = i
	for i in range(len(s)):
		if s[i] == '3':
			i3 = i
	mi = max(i1, i2, i3) - min(i1, i2, i3)
	for i in range(len(s)):
		if s[i] == '1':
			i1 = i
		elif s[i] == '2':
			i2 = i
		else:
			i3 = i
		mi = min(mi, max(i1, i2, i3) - min(i1, i2, i3))
	print(mi + 1)


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
main()


t = int(input())
while t:
	t = t - 1
	s = input()
	flag = 0
	l = []
	if '1' not in s:
		print(0)
		continue
	elif '2' not in s:
		print(0)
		continue
	elif '3' not in s:
		print(0)
		continue
	else:
		k = []
		ans = 0
		w = 0
		while w < len(s):
			if s[w] not in k:
				k.append(s[w])
				ans += 1
			elif s[w] in k and len(k) != 1:
				if k[-1] == s[w]:
					ans += 1
				else:
					ans = 2
					temp = k[-1]
					k = [temp, s[w]]
			if len(k) == 3:
				l.append(ans)
				k = [k[-2], k[-1]]
				ans = 2
			w += 1
	if l == []:
		print(0)
	else:
		print(min(l))


import os
import sys
from io import BytesIO, IOBase

def main():
	pass
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))
input = lambda : sys.stdin.readline().rstrip('\r\n')
from collections import defaultdict
t = int(input())
while t:
	s = input()
	d = defaultdict(int)
	count = 0
	a = -1
	b = -1
	c = -1
	i = 0
	n = len(s)
	ans = float('inf')
	while i < n:
		if s[i] == '1':
			a = i
		if s[i] == '2':
			b = i
		if s[i] == '3':
			c = i
		if a != -1 and b != -1 and (c != -1):
			ans = min(ans, max(a, b, c) - min(a, b, c))
		i += 1
	print(ans + 1) if ans != float('inf') else print(0)
	t -= 1


import os
import sys
from io import BytesIO, IOBase
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))
input = lambda : sys.stdin.readline().rstrip('\r\n')
import math

def fact(x):
	if x == 0:
		return 1
	else:
		return x * fact(x - 1)

def lower_bound(li, num):
	answer = -1
	start = 0
	end = len(li) - 1
	while start <= end:
		middle = (end + start) // 2
		if li[middle] >= num:
			answer = middle
			end = middle - 1
		else:
			start = middle + 1
	return answer

def upper_bound(li, num):
	answer = -1
	start = 0
	end = len(li) - 1
	while start <= end:
		middle = (end + start) // 2
		if li[middle] <= num:
			answer = middle
			start = middle + 1
		else:
			end = middle - 1
	return answer

def abs(x):
	return x if x >= 0 else -x

def binary_search(li, val, lb, ub):
	ans = 0
	while lb <= ub:
		mid = (lb + ub) // 2
		if li[mid] > val:
			ub = mid - 1
		elif val > li[mid]:
			lb = mid + 1
		else:
			ans = 1
			break
	return ans
import math
for _ in range(int(input())):
	string = input()
	n = len(string)
	entry = [0, 0, 0]
	for i in range(n):
		entry[int(string[i]) - 1] += 1
		if 0 not in entry:
			break
	if 0 in entry:
		print(0)
		continue
	start = 0
	while 0 not in entry:
		entry[int(string[start]) - 1] -= 1
		start += 1
	len1 = sum(entry) + 1
	string = string[::-1]
	entry = [0, 0, 0]
	for i in range(n):
		entry[int(string[i]) - 1] += 1
		if 0 not in entry:
			break
	start = 0
	while 0 not in entry:
		entry[int(string[start]) - 1] -= 1
		start += 1
	len2 = sum(entry) + 1
	len3 = 2000000
	for i in range(n - 2):
		entry = [0, 0, 0]
		entry[int(string[i]) - 1] += 1
		entry[int(string[i + 1]) - 1] += 1
		entry[int(string[i + 2]) - 1] += 1
		if 0 not in entry:
			len3 = 3
	temp = min(len1, len2)
	print(min(temp, len3))


t = int(input())
for i in range(t):
	s = input()
	condensed = list()
	counts = list()
	curele = s[0]
	count = 0
	for j in range(len(s)):
		if s[j] == curele:
			count += 1
		else:
			condensed.append(s[j - 1])
			curele = s[j]
			counts.append(count)
			count = 1
	condensed.append(curele)
	counts.append(count)
	moves = []
	for j in range(len(condensed) - 2):
		l = j
		r = j + 2
		temp = condensed[l:r + 1]
		if '1' in temp and '2' in temp and ('3' in temp):
			moves.append(counts[(l + r) // 2] + 2)
	if moves:
		print(min(moves))
	else:
		print(0)


import sys
trials = int(input())
for trial in range(trials):
	s = input()
	dt = dict()
	flag = False
	res = sys.maxsize
	for (ind, c) in enumerate(s):
		dt[c] = ind
		if len(dt) == 3:
			res = min(res, max(dt.values()) - min(dt.values()) + 1)
	if res != sys.maxsize:
		print(res)
	else:
		print(0)


from sys import stdin, stdout
import math
t = int(stdin.readline())
for _ in range(t):
	s = stdin.readline().strip()
	ans = float('inf')
	(c1, c2, c3) = (None, None, None)
	seen_all = False
	for (i, c) in enumerate(s):
		if c == '1':
			c1 = i + 1
		elif c == '2':
			c2 = i + 1
		elif c == '3':
			c3 = i + 1
		if seen_all:
			ans = min(ans, max(c1, c2, c3) - min(c1, c2, c3) + 1)
		if c1 and c2 and c3:
			seen_all = True
			ans = min(ans, max(c1, c2, c3) - min(c1, c2, c3) + 1)
	print(0 if ans == float('inf') else ans)


def main():
	s = input()
	best = 10 ** 9
	(c, n) = ([], len(s))
	for i in s:
		if len(c) == 0 or c[-1][0] != i:
			c.append([i, 1])
		else:
			c[-1][1] += 1
	for i in range(1, len(c) - 1):
		if c[i - 1][0] != c[i + 1][0]:
			best = min(best, c[i][1] + 2)
	if best > n:
		print('0')
	else:
		print(best)
for _ in range(int(input())):
	main()


t = int(input())
while t > 0:
	t -= 1
	n = input()
	s = list(n)
	l = 0
	ans = 10 ** 9
	m = []
	m = [0] * 100
	for r in range(len(s)):
		x = int(s[r]) - 1
		m[x] += 1
		while m[int(s[l]) - 1] > 1:
			m[int(s[l]) - 1] -= 1
			l += 1
		if m[0] and m[1] and m[2]:
			ans = min(ans, r - l + 1)
	if ans > 10 ** 7:
		ans = 0
	print(ans)


def lenth(s):
	d = {}
	t = '123'
	tlen = len(t)
	start = 0
	for i in t:
		if i in d:
			d[i] += 1
		else:
			d[i] = 1
	minl = float('inf')
	matched = 0
	ws = 0
	we = 0
	for we in range(len(s)):
		if s[we] in d:
			d[s[we]] -= 1
			if d[s[we]] >= 0:
				matched += 1
		while matched == tlen:
			if minl > we - ws + 1:
				minl = we - ws + 1
				start = ws
			left_char = s[ws]
			ws += 1
			if left_char in d:
				if d[left_char] == 0:
					matched -= 1
				d[left_char] += 1
	if minl == float('inf'):
		return 0
	return minl
t = int(input())
for _ in range(t):
	s = input()
	print(lenth(s))


from sys import stdin, stdout
inp = stdin.readline
out = stdout.write
for _ in range(int(inp())):
	st = inp()
	n = len(st) - 1
	start = 0
	best = int(1000000000.0)
	unq = 3
	unq_a = set()
	for i in range(0, n):
		if st[i] in unq_a:
			if i - 1 >= 0:
				if st[i - 1] != st[i]:
					start = i - 1
		else:
			unq -= 1
			if unq != 0:
				unq_a.add(st[i])
				start = i - 1 if i - 1 >= 0 else 0
			else:
				best = min(best, i - start + 1)
				unq_a.clear()
				unq_a.add(st[i])
				unq_a.add(st[i - 1])
				unq = 1
				start = i - 1
	if best > n:
		best = 0
	out(str(best) + '\n')


import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	s = list(input().rstrip())
	idxArr = [0] * 3
	(flg1, flg2, flg3) = (False, False, False)
	ans = float('inf')
	for i in range(len(s)):
		if int(s[i]) == 1:
			flg1 = True
		elif int(s[i]) == 2:
			flg2 = True
		else:
			flg3 = True
		idxArr[int(s[i]) - 1] = i
		if flg1 and flg2 and flg3:
			ans = min(ans, max(idxArr) - min(idxArr) + 1)
	if ans == float('inf'):
		print(0)
	else:
		print(ans)


for _ in range(int(input())):
	fef = input()
	(sus, dp) = (200001, [0, 0, 0])
	for j in range(len(fef)):
		dp[int(fef[j]) - 1] = j + 1
		if all(dp):
			sus = min(sus, max(dp) - min(dp) + 1)
			if sus == 3:
				break
			dp[dp.index(min(dp))] = 0
	print(sus if sus != 200001 else 0)


t = int(input())
a1 = '1'
a2 = '2'
a3 = '3'
for _ in range(t):
	s = input()
	max_str = 0
	l_str = 0
	st = ''
	a = ['1', '2', '3']
	if a1 in s and a2 in s and (a3 in s):
		for i in s:
			if a:
				if i in a:
					a.remove(i)
				st += i
			if not a:
				j = 1
				t = 0
				while st[0] == st[j]:
					t += 1
					j += 1
				l_str = len(st) - t
				if max_str == 0:
					max_str = l_str
				max_str = min(max_str, l_str)
				a = ['1', '2', '3']
				stt = ''
				for k in st[::-1]:
					if a:
						if k in a:
							a.remove(k)
						stt += k
					if not a:
						j = 1
						t = 0
						while stt[0] == stt[j]:
							t += 1
							j += 1
						max_str = min(max_str, len(stt) - t)
						break
				a = ['1', '2', '3']
				a.remove(st[-1])
				a.remove(st[-2])
				st = st[-2] + st[-1]
		print(max_str)
	else:
		print(0)


t = int(input())
for _ in range(t):
	s = input()
	n = len(s)
	ans = float('inf')
	d = [-1] * 4
	for i in range(n):
		d[int(s[i])] = int(i)
		if d[1] > -1 and d[2] > -1 and (d[3] > -1):
			_max = max(d[1:])
			_min = min(d[1:])
			ans = min(ans, _max - _min + 1)
	if ans == float('inf'):
		print(0)
	else:
		print(ans)


def isvalid(k, s):
	a = [0, 0, 0, 0]
	for i in range(k - 1):
		ind = int(s[i])
		a[ind] += 1
	for i in range(k - 1, len(s)):
		ind = int(s[i])
		a[ind] += 1
		if a[1] > 0 and a[2] > 0 and (a[3] > 0):
			return 1
		ind = int(s[i - k + 1])
		a[ind] -= 1
	return 0
for t in range(int(input())):
	s = input()
	res = 10 ** 10
	left = 3
	right = len(s)
	ans = 10 ** 10
	while left <= right:
		mid = left + (right - left) // 2
		if isvalid(mid, s):
			ans = min(ans, mid)
			right = mid - 1
		else:
			left = mid + 1
	if ans == 10 ** 10:
		print(0)
	else:
		print(ans)


from math import *
t = int(input())
for i in range(t):
	s = input()
	ind1 = -1
	ind2 = -1
	ind3 = -1
	l = []
	for j in range(len(s)):
		if s[j] == '1':
			ind1 = j
		if s[j] == '2':
			ind2 = j
		if s[j] == '3':
			ind3 = j
		if ind1 != -1 and ind2 != -1 and (ind3 != -1):
			l.append(max(ind1, ind2, ind3) - min(ind1, ind2, ind3) + 1)
	if len(l) == 0:
		print(0)
	else:
		print(min(l))


from math import *
t = int(input())
while t > 0:
	s = input()
	n = len(s)
	a = 0
	b = 0
	c = 0
	l = 0
	m = n + 1
	for i in range(n):
		if s[i] == '1':
			a += 1
		elif s[i] == '2':
			b += 1
		elif s[i] == '3':
			c += 1
		while True:
			check = 0
			while s[l] == '1' and a > 1:
				l += 1
				a -= 1
				check += 1
			while s[l] == '2' and b > 1:
				l += 1
				b -= 1
				check += 1
			while s[l] == '3' and c > 1:
				l += 1
				c -= 1
				check += 1
			if check == 0:
				break
		if a > 0 and b > 0 and (c > 0) and (m > i - l + 1):
			m = i - l + 1
	if m > n:
		print(0)
	else:
		print(m)
	t -= 1


from math import *
a = int(input())
for i in range(a):
	s = input()
	mn = len(s) + 1
	l = [-1] * 3
	for i in range(len(s)):
		l[int(s[i]) % 3] = i
		n = min(l)
		x = max(l)
		if n != -1 and x - n + 1 < mn:
			mn = x - n + 1
	if mn == len(s) + 1:
		print(0)
	else:
		print(mn)


t = int(input())
while t > 0:
	string = input()
	l = len(string)
	map = {1: -1, 2: -1, 3: -1}
	m = float('inf')
	for i in range(0, l):
		map[int(string[i])] = i
		if map[1] != -1 and map[2] != -1 and (map[3] != -1):
			if max(map.values()) - min(map.values()) < m:
				m = max(map.values()) - min(map.values()) + 1
	if map[1] == -1 or map[2] == -1 or map[3] == -1:
		print(0)
	else:
		print(m)
	t -= 1


import math
for _ in range(int(input())):
	s = input()
	l = list(s)
	n = len(s)
	if l.count('1') == 0 or l.count('2') == 0 or l.count('3') == 0:
		print(0)
	else:
		a = []
		i1 = -1
		i2 = -1
		i3 = -1
		for i in range(n):
			if l[i] == '1':
				i1 = i
			if l[i] == '2':
				i2 = i
			if l[i] == '3':
				i3 = i
			if i1 != -1 and i2 != -1 and (i3 != -1):
				a.append(max(i1, i2, i3) - min(i1, i2, i3) + 1)
		print(min(a))


for _ in range(int(input())):
	s = input()
	first = s[0]
	length = 1
	second = ''
	best = 2000000
	for i in range(1, len(s)):
		if s[i] != first and second == '':
			second = s[i]
			length += 1
		elif s[i] == first and second != '':
			(first, second) = (second, first)
			length = 2
		elif s[i] == second:
			length += 1
		elif s[i] != first and s[i] != second:
			length += 1
			best = min(best, length)
			(first, second) = (second, s[i])
			length = 2
	print(best) if best != 2000000 else print(0)


import sys
import math
import heapq

def ii():
	return sys.stdin.readline().strip()

def idata():
	return [int(x) for x in ii().split()]

def solve_of_problem():
	s = input()
	ans_2 = [int(s[0])]
	ans_1 = [1]
	for j in range(1, len(s)):
		if int(s[j]) == ans_2[-1]:
			ans_1[-1] += 1
		else:
			ans_2 += [int(s[j])]
			ans_1 += [1]
	ans = 200005
	for j in range(2, len(ans_2)):
		if ans_2[j - 2] + ans_2[j - 1] + ans_2[j] == 6:
			ans = min(ans, ans_1[j - 1] + 2)
	if ans != 200005:
		print(ans)
	else:
		print(0)
	return
for ______ in range(int(ii())):
	solve_of_problem()


for _ in range(int(input())):
	s = input()
	a = [0, 0, 0]
	ans = 1000000.0
	j = 1
	for i in s:
		if i == '1':
			a[0] = j
		elif i == '2':
			a[1] = j
		else:
			a[2] = j
		if all(a):
			ans = min(ans, j - min(a) + 1)
		j += 1
	if ans == 1000000.0:
		print(0)
	else:
		print(ans)


for _ in range(int(input())):
	s = input()
	if len(set(s)) < 3:
		print(0)
	else:
		(f1, f2, f3) = (0, 0, 0)
		(p1, p2, p3) = (0, 0, 0)
		ans = []
		for i in range(len(s)):
			if s[i] == '1':
				f1 = 1
				p1 = i
			elif s[i] == '2':
				f2 = 1
				p2 = i
			else:
				f3 = 1
				p3 = i
			if f1 and f2 and f3:
				st = min(p1, min(p2, p3))
				en = max(p1, max(p2, p3))
				ans.append(en - st + 1)
		print(min(ans))


from sys import stdin
input = stdin.readline

def min(x, y):
	return x if x < y else y

def max(x, y):
	return x if x > y else y
for _ in range(int(input())):
	s = list(map(int, input().strip()))
	d = {}
	mini = float('inf')
	for (j, i) in enumerate(s):
		d[i] = j
		if 1 in d and 2 in d and (3 in d):
			if i == 1:
				mini = min(mini, j - min(d[2], d[3]) + 1)
			if i == 2:
				mini = min(mini, j - min(d[1], d[3]) + 1)
			if i == 3:
				mini = min(mini, j - min(d[1], d[2]) + 1)
	if mini == float('inf'):
		print(0)
	else:
		print(mini)


for T in range(int(input())):
	s = input()
	visit = [-1] * 3
	mn = 1000000000.0
	for i in range(len(s)):
		if s[i] == '1':
			visit[0] = i
		elif s[i] == '2':
			visit[1] = i
		else:
			visit[2] = i
		a = min(visit)
		b = max(visit)
		if a != -1 and b != -1:
			mn = min(mn, b - a)
	if mn == 1000000000.0:
		print(0)
	else:
		print(mn + 1)


t = int(input())
while t:
	t -= 1
	s = input()
	a = -1
	b = -1
	c = -1
	ans = 1000000000
	for i in range(0, len(s)):
		if s[i] == '1':
			a = i
		elif s[i] == '2':
			b = i
		else:
			c = i
		if a != -1 and b != -1 and (c != -1):
			a1 = max(a, b, c)
			b2 = min(a, b, c)
			ans = min(ans, a1 - b2 + 1)
	if ans == 1000000000:
		print('0')
	else:
		print(ans)


for _ in range(int(input())):
	s = input()
	ds = [-1000000000.0, -1000000000.0, -1000000000.0]
	res = int(1000000000.0)
	for i in range(len(s)):
		ds[int(s[i]) - 1] = i
		res = min(res, i - min(ds[0], ds[1], ds[2]))
	if res > 100000000.0:
		res = -1
	print(res + 1)


a = int(input())
for _ in range(a):
	b = input()
	c = len(b)
	t = []
	x = 0
	y = 0
	z = 0
	for q in range(c):
		if x == 1 and y == 0 and (z == 0):
			if b[q] == '1':
				continue
			elif b[q] == '2':
				y += 1
			else:
				z += 1
		elif x == 0 and y == 1 and (z == 0):
			if b[q] == '2':
				continue
			elif b[q] == '1':
				x += 1
			else:
				z += 1
		elif x == 0 and y == 0 and (z == 1):
			if b[q] == '3':
				continue
			elif b[q] == '1':
				x += 1
			else:
				y += 1
		elif b[q] == '1':
			x += 1
		elif b[q] == '2':
			y += 1
		else:
			z += 1
		if x > 0 and y > 0 and (z > 0):
			t.append(x + y + z)
			if b[q - 1] == '1' and b[q - 2] == '2':
				t.append(3)
				x = 0
				y = 0
				z = 0
			elif b[q - 1] == '1' and b[q - 2] == '3':
				t.append(3)
				x = 0
				y = 0
				z = 0
			elif b[q - 1] == '1' and b[q - 2] == '1' and (b[q] == '2'):
				j = b[q::-1]
				p = j.index('3')
				t.append(p + 1)
				x = 1
				y = 1
				z = 0
			elif b[q - 1] == '1' and b[q - 2] == '1' and (b[q] == '3'):
				j = b[q::-1]
				p = j.index('2')
				t.append(p + 1)
				x = 1
				y = 0
				z = 1
			elif b[q - 1] == '2' and b[q - 2] == '1':
				t.append(3)
				x = 0
				y = 0
				z = 0
			elif b[q - 1] == '2' and b[q - 2] == '3':
				t.append(3)
				x = 0
				y = 0
				z = 0
			elif b[q - 1] == '2' and b[q - 2] == '2' and (b[q] == '1'):
				j = b[q::-1]
				p = j.index('3')
				t.append(p + 1)
				x = 1
				y = 1
				z = 0
			elif b[q - 1] == '2' and b[q - 2] == '2' and (b[q] == '3'):
				j = b[q::-1]
				p = j.index('1')
				t.append(p + 1)
				x = 0
				y = 1
				z = 1
			elif b[q - 1] == '3' and b[q - 2] == '1':
				t.append(3)
				x = 0
				y = 0
				z = 0
			elif b[q - 1] == '3' and b[q - 2] == '2':
				t.append(3)
				x = 0
				y = 0
				z = 0
			elif b[q - 1] == '3' and b[q - 2] == '3' and (b[q] == '1'):
				j = b[q::-1]
				p = j.index('2')
				t.append(p + 1)
				x = 1
				y = 0
				z = 1
			elif b[q - 1] == '3' and b[q - 2] == '3' and (b[q] == '2'):
				j = b[q::-1]
				p = j.index('1')
				t.append(p + 1)
				x = 0
				y = 1
				z = 1
	if len(t) == 0:
		print(0)
	else:
		print(min(t))


def fill(table, s):
	last1 = -1
	last2 = -1
	last3 = -1
	index = 0
	for c in s:
		value = int(c)
		if value == 1:
			last1 = index
		elif value == 2:
			last2 = index
		elif value == 3:
			last3 = index
		if last1 != -1:
			table[0][index] = min(table[0][index], abs(last1 - index))
		if last2 != -1:
			table[1][index] = min(table[1][index], abs(last2 - index))
		if last3 != -1:
			table[2][index] = min(table[2][index], abs(last3 - index))
		index += 1
	last1 = -1
	last2 = -1
	last3 = -1
	index = len(s) - 1
	for c in reversed(s):
		value = int(c)
		if value == 1:
			last1 = index
		elif value == 2:
			last2 = index
		elif value == 3:
			last3 = index
		if last1 != -1:
			table[0][index] = min(table[0][index], abs(last1 - index))
		if last2 != -1:
			table[1][index] = min(table[1][index], abs(last2 - index))
		if last3 != -1:
			table[2][index] = min(table[2][index], abs(last3 - index))
		index -= 1

def task(s):
	n = len(s)
	table = [[1000000] * n, [1000000] * n, [1000000] * n]
	fill(table, s)
	mn = 1000000
	for i in range(0, n):
		suma = table[0][i] + table[1][i] + table[2][i] + 1
		mn = min(mn, suma)
	if mn == 1000000:
		print(0)
		return
	print(mn)
t = int(input())
for i in range(0, t):
	s = input()
	task(s)


t = int(input())
while t:
	t -= 1
	data = input()
	if '1' not in data:
		print(0)
		continue
	if '2' not in data:
		print(0)
		continue
	if '3' not in data:
		print(0)
		continue
	index_1 = -1
	index_2 = -1
	index_3 = -1
	ans = 200001
	for i in range(len(data)):
		if data[i] == '1':
			index_1 = i
		if data[i] == '2':
			index_2 = i
		if data[i] == '3':
			index_3 = i
		if index_1 != -1 and index_2 != -1 and (index_3 != -1):
			ww = [index_1, index_2, index_3]
			tmp = max(ww)
			tmp2 = min(ww)
			res = tmp - tmp2
			if res < ans:
				ans = res
			cc = ww.index(tmp2)
			if cc == 0:
				index_1 = -1
			elif cc == 1:
				index_2 = -1
			else:
				index_3 = -1
	print(ans + 1)


import collections
import operator
for _ in range(int(input())):
	ll = [int(i) for i in list(input())]
	d = collections.defaultdict(list)
	size = len(ll)
	for i in range(size):
		d[ll[i]].append(i)
	if len(d) < 3:
		print(0)
		continue
	i1 = -1
	i2 = -1
	i3 = -1
	res = 0
	mx = float('inf')
	for i in range(size):
		if ll[i] == 1:
			i1 = i
		elif ll[i] == 2:
			i2 = i
		else:
			i3 = i
		if i1 >= 0 and i2 >= 0 and (i3 >= 0):
			res = max([i1, i2, i3]) + 1 - min([i1, i2, i3])
			mx = min(mx, res)
	print(mx)


n = int(input())
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 _ in range(n):
	s = input()
	print(len(findSubString(s, '123')))


import math
import os
import random
import re
import sys
from collections import OrderedDict

def solve():
	for _ in range(int(input())):
		s = input()
		n = len(s)
		if '1' in s and '2' in s and ('3' in s):
			c = 1
			o = []
			l = []
			for i in range(1, n):
				if s[i] == s[i - 1]:
					c += 1
				else:
					o.append(s[i - 1])
					l.append(c)
					c = 1
			o.append(s[i])
			l.append(c)
			on = len(o)
			ln = len(l)
			cf = 0
			t = []
			for i in range(on - 2):
				if o[i] != o[i + 1] and o[i] != o[i + 2] and (o[i + 1] != o[i + 2]):
					t.append(l[i + 1] + 2)
				else:
					continue
			print(min(t))
		else:
			print(0)
solve()


def ProcessInputs():
	S = input()
	D = {}
	L = 9999999999
	for i in range(len(S)):
		D[S[i]] = i
		if '1' in D and '2' in D and ('3' in D):
			m = min(D['1'], D['2'], D['3'])
			M = max(D['1'], D['2'], D['3'])
			L = min(L, M - m + 1)
	if L == 9999999999:
		print(0)
		return
	print(L)
T = int(input())
for _ in range(T):
	ProcessInputs()


def solve(s):
	count1 = count2 = count3 = 0
	low = 0
	high = 0
	min_len = float('inf')
	while low <= high:
		if count1 < 1 or count2 < 1 or count3 < 1:
			if high == len(s):
				break
			if s[high] == '1':
				count1 += 1
			elif s[high] == '2':
				count2 += 1
			else:
				count3 += 1
			high += 1
		elif count1 >= 1 and count2 >= 1 and (count3 >= 1):
			min_len = min(min_len, high - low)
			if s[low] == '1':
				count1 -= 1
			elif s[low] == '2':
				count2 -= 1
			else:
				count3 -= 1
			low += 1
	if min_len == float('inf'):
		print(0)
		return
	print(min_len)
t = int(input())
for _ in range(t):
	arr = input().rstrip()
	solve(arr)


t = int(input())
while t:
	t = t - 1
	s = input()
	count = {'1': 0, '2': 0, '3': 0}
	min_len = float('inf')
	start = 0
	start_index = -1
	if len(s) < 3:
		print(0)
		continue
	found = 0
	for j in range(0, len(s)):
		count[s[j]] = count[s[j]] + 1
		if count[s[j]] == 1:
			found = found + 1
		if found == 3:
			s1 = start
			while True:
				ch = s[s1]
				if count[ch] == 1:
					break
				s1 = s1 + 1
				count[ch] = count[ch] - 1
			l = j - s1 + 1
			if l < min_len:
				min_len = l
				start_index = s1
			start = s1 + 1
			count[s[s1]] = count[s[s1]] - 1
			found = found - 1
	if start_index == -1:
		print(0)
	else:
		print(min_len)


from sys import stdin, stdout
for _ in range(int(input())):
	s = input()
	n = len(s)
	(i, j) = (0, 0)
	cnt = [1, 0, 0, 0]
	l = int(1000000.0)
	while 1:
		while j < n and (not all(cnt)):
			cnt[int(s[j])] += 1
			j += 1
		while i < j and all(cnt):
			l = min(l, j - i)
			cnt[int(s[i])] -= 1
			i += 1
		if j == n:
			break
	print(l if l != int(1000000.0) else 0)


from collections import Counter
full = frozenset('123')
for _ in range(int(input())):
	s = input()
	if frozenset(s) != full:
		print(0)
	else:
		cnt = Counter()
		n = len(s)
		ans = n
		r = 0
		for li in range(n):
			while frozenset(cnt.keys()) != full:
				if r == n:
					break
				cnt[s[r]] += 1
				r += 1
			else:
				ans = min(ans, r - li)
				cnt[s[li]] -= 1
				if not cnt[s[li]]:
					del cnt[s[li]]
				continue
			break
		print(ans)


t = int(input())
for _ in range(t):
	s = list(input())
	a = len(s)
	ans = []
	k = 0
	j = 0
	c = 0
	ans1 = 0
	while j < a:
		l = []
		d = {}
		while j < a and len(l) < 3:
			if s[j] not in l:
				l.append(s[j])
				d[s[j]] = 1
			else:
				d[s[j]] += 1
			j += 1
		if len(d.keys()) == 3:
			while d['1'] > 0 and d['2'] > 0 and (d['3'] > 0) and (k < a):
				d[s[k]] -= 1
				if d[s[k]] == 0:
					d[s[k]] += 1
					k += 1
					break
				k += 1
			j = k
			ans1 = d['1'] + d['2'] + d['3']
		else:
			j = a
		if ans1 == 3:
			ans.append(ans1)
			break
		elif len(d.keys()) >= 3:
			ans.append(ans1)
	if len(ans) < 1:
		print(0)
	else:
		print(min(ans))


import sys

def findCloset(A, B, C, p, q, r):
	diff = sys.maxsize
	res_i = 0
	res_j = 0
	res_k = 0
	i = 0
	j = 0
	k = 0
	while i < p and j < q and (k < r):
		minimum = min(A[i], min(B[j], C[k]))
		maximum = max(A[i], max(B[j], C[k]))
		if maximum - minimum < diff:
			res_i = i
			res_j = j
			res_k = k
			diff = maximum - minimum
		if diff == 0:
			break
		if A[i] == minimum:
			i = i + 1
		elif B[j] == minimum:
			j = j + 1
		else:
			k = k + 1
	arr = [A[res_i], B[res_j], C[res_k]]
	arr.sort()
	return max(arr) - min(arr)
t = int(input())
while t > 0:
	s = list(input())
	a1 = []
	a2 = []
	a3 = []
	for i in range(len(s)):
		if s[i] == '1':
			a1.append(i)
		elif s[i] == '2':
			a2.append(i)
		else:
			a3.append(i)
	n1 = len(a1)
	n2 = len(a2)
	n3 = len(a3)
	if n1 == 0 or n2 == 0 or n3 == 0:
		print(0)
	else:
		ans = findCloset(a1, a2, a3, n1, n2, n3)
		print(ans + 1)
	t -= 1


def main():
	s = input()
	first = 0
	prev = s[0]
	second = 0
	first_x = prev
	second_x = None
	res = len(s) + 1
	for i in range(1, len(s)):
		x = s[i]
		if x != prev:
			second = i
			second_x = x
			first = second - 1
			first_x = s[i - 1]
			prev = x
			break
		prev = x
	if second == len(s) - 1 or not second:
		print(0)
		return
	for i in range(second + 1, len(s)):
		x = s[i]
		if x != prev:
			if x != first_x:
				res = min(res, i - first + 1)
			second = i
			second_x = x
			first = second - 1
			first_x = s[i - 1]
			prev = x
		prev = x
	if res == len(s) + 1:
		print(0)
	else:
		print(res)
for _ in range(int(input())):
	main()


for _ in range(int(input())):
	s = input()
	temp = [s[0]]
	last = s[0]
	times = 1
	test = []
	for i in range(1, len(s)):
		if last == s[i]:
			times += 1
			pass
		else:
			test.append(times)
			temp.append(s[i])
			last = s[i]
			times = 1
	if times != 0:
		test.append(times)
		temp.append(s[len(s) - 1])
	i = 0
	ans = len(s) + 100
	while i < len(temp) - 2:
		if set(temp[i:i + 3]) == {'1', '2', '3'}:
			ans = min(ans, 2 + test[i + 1])
		i += 1
	if ans > len(s):
		print(0)
	else:
		print(ans)


from sys import stdin, stdout
int_in = lambda : int(stdin.readline())
arr_in = lambda : [int(x) for x in stdin.readline().split()]
mat_in = lambda rows: [arr_in() for y in range(rows)]
str_in = lambda : stdin.readline().strip()
out = lambda o: stdout.write('{}\n'.format(o))
arr_out = lambda o: out(' '.join(map(str, o)))
bool_out = lambda o: out('YES' if o else 'NO')

def solve(s):
	if len(set(s)) != 3:
		return 0
	counts = [0, 0, 0]
	p1 = 0
	p2 = 0
	counts[s[p1]] += 1
	best = float('inf')
	while p1 < len(s):
		while p2 < len(s) - 1 and 0 in counts and (p2 - p1 + 1 < best):
			p2 += 1
			counts[s[p2]] += 1
		if 0 not in counts:
			best = min(best, p2 - p1 + 1)
		counts[s[p1]] -= 1
		p1 += 1
	return best
for i in range(int_in()):
	s = [int(x) - 1 for x in str_in()]
	out(solve(s))


from collections import defaultdict as dfd
import math
import sys

def II():
	return int(sys.stdin.readline())

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

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

def LLI(rows_number):
	return [LI() for _ in range(rows_number)]

def main():
	for _ in range(int(input())):
		A = input()
		A = list(A)
		B = ['1', '2', '3']
		C = []
		mini = 2 * 10 ** 6
		j = 0
		plp = 0
		i = 0
		val = dfd(int)
		while i < len(A):
			if val['1'] != 0 and val['2'] != 0 and (val['3'] != 0):
				mini = min(i - j, mini)
				val[A[j]] -= 1
				j += 1
				plp = 1
				if mini == 3:
					break
			else:
				val[A[i]] += 1
				i += 1
		if plp == 0:
			if val['1'] != 0 and val['2'] != 0 and (val['3'] != 0):
				mini = min(i - j, mini)
				while j < i and val['1'] != 0 and (val['2'] != 0) and (val['3'] != 0):
					mini = min(i - j, mini)
					val[A[j]] -= 1
					j += 1
				print(mini)
			else:
				print(0)
		else:
			if val['1'] != 0 and val['2'] != 0 and (val['3'] != 0):
				while j < i and val['1'] != 0 and (val['2'] != 0) and (val['3'] != 0):
					mini = min(i - j, mini)
					val[A[j]] -= 1
					j += 1
			print(mini)
main()


import sys
input = sys.stdin.readline
import bisect
t = int(input())
for tests in range(t):
	S = input().strip()
	ONE = [-1 << 31]
	TWO = [-1 << 31]
	THREE = [-1 << 31]
	for i in range(len(S)):
		if S[i] == '1':
			ONE.append(i)
		elif S[i] == '2':
			TWO.append(i)
		else:
			THREE.append(i)
	ONE.append(1 << 31)
	TWO.append(1 << 31)
	THREE.append(1 << 31)
	ANS = 1 << 31
	for i in range(len(S)):
		if S[i] == '1':
			x0 = bisect.bisect_left(TWO, i)
			x1 = bisect.bisect_left(THREE, i)
			ANS = min(ANS, TWO[x0] - THREE[x1 - 1] + 1, THREE[x1] - TWO[x0 - 1] + 1)
		elif S[i] == '2':
			x0 = bisect.bisect_left(ONE, i)
			x1 = bisect.bisect_left(THREE, i)
			ANS = min(ANS, ONE[x0] - THREE[x1 - 1] + 1, THREE[x1] - ONE[x0 - 1] + 1)
		else:
			x0 = bisect.bisect_left(ONE, i)
			x1 = bisect.bisect_left(TWO, i)
			ANS = min(ANS, ONE[x0] - TWO[x1 - 1] + 1, TWO[x1] - ONE[x0 - 1] + 1)
	if ANS >= 1 << 30:
		print(0)
	else:
		print(ANS)


import sys
sys.setrecursionlimit(10 ** 6)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep='\n')

def II():
	return int(sys.stdin.readline())

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

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

def LLI(rows_number):
	return [LI() for _ in range(rows_number)]

def SI():
	return sys.stdin.readline()[:-1]

def main():
	for _ in range(II()):
		inf = 10 ** 9
		aa = [int(c) - 1 for c in SI()]
		last = [inf] * 3
		n = len(aa)
		ans = inf
		for i in range(n):
			last[aa[i]] = i
			if sum(last) < inf:
				ans = min(ans, i - min(last) + 1)
				li = last.index(min(last))
				last[li] = inf
		if ans == inf:
			print(0)
		else:
			print(ans)
main()


from collections import defaultdict
import sys

def SmallestSubString(S):
	distinct_count = len(set(list(S)))
	n = len(S)
	freq = defaultdict(int)
	start_idx = 0
	min_len = sys.maxsize
	distinct_till_here = 0
	for j in range(n):
		freq[S[j]] += 1
		if freq[S[j]] == 1:
			distinct_till_here += 1
		if distinct_count == distinct_till_here:
			while freq[S[start_idx]] > 1:
				if freq[S[start_idx]] > 1:
					freq[S[start_idx]] -= 1
				start_idx += 1
			curr_len = j - start_idx + 1
			min_len = min(min_len, curr_len)
	return min_len
t = int(input())
for _ in range(t):
	s = input()
	l = list(s)
	val1 = -1
	for i in range(len(l)):
		if l[i] == '1':
			val1 = i
			break
	val2 = -1
	for i in range(len(l)):
		if l[i] == '2':
			val2 = i
			break
	val3 = -1
	for i in range(len(l)):
		if l[i] == '3':
			val3 = i
			break
	if val1 == -1 or val2 == -1 or val3 == -1:
		print(0)
	else:
		print(SmallestSubString(s))


t = int(input())
for i in range(t):
	s = input()
	u = len(s)
	if len(s) < 3 or s.count('1') == 0 or s.count('2') == 0 or (s.count('3') == 0):
		print(0)
	else:
		l = 0
		r = 0
		(k1, k2, k3) = (0, 0, 0)
		ans = 200000
		while r != u and l != u - 2:
			if not (k1 and k2 and k3):
				if s[r] == '1':
					k1 += 1
				if s[r] == '2':
					k2 += 1
				if s[r] == '3':
					k3 += 1
			else:
				if s[l] == '1':
					k1 -= 1
				if s[l] == '2':
					k2 -= 1
				if s[l] == '3':
					k3 -= 1
				l += 1
			if k1 and k2 and k3:
				ans = min(ans, r + 1 - l)
			else:
				r += 1
		print(ans)


from itertools import *
for s in [*open(0)][1:]:
	p = q = 0
	r = m = 4 ** 9
	for (k, g) in groupby(s[:-1]):
		if (p or k) != k:
			r = min(r, l + 2)
		l = len([*g])
		p = q
		q = k
	print(r % m)


t = int(input())
for g in range(0, t):
	s = input()
	a = -1
	b = -1
	c = -1
	ans = len(s)
	temp = []
	for i in range(0, len(s)):
		temp.append(s[i])
	temp = set(temp)
	if len(set(temp)) != 3:
		ans = 0
	for i in range(0, len(s)):
		if s[i] == '1':
			a = i
		elif s[i] == '2':
			b = i
		else:
			c = i
		if a >= 0 and b >= 0 and (c >= 0):
			ans = min(ans, max(a, b, c) - min(a, b, c) + 1)
	print(ans)


import sys
import math
import itertools
import functools
import collections
import operator
import fileinput
import copy
from collections import *
ORDA = 97

def ii():
	return int(input())

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

def li():
	return [int(i) for i in input().split()]

def lcm(a, b):
	return abs(a * b) // math.gcd(a, b)

def revn(n):
	return str(n)[::-1]

def dd():
	return collections.defaultdict(int)

def ddl():
	return collections.defaultdict(list)

def sieve(n):
	if n < 2:
		return list()
	prime = [True for _ in range(n + 1)]
	p = 3
	while p * p <= n:
		if prime[p]:
			for i in range(p * 2, n + 1, p):
				prime[i] = False
		p += 2
	r = [2]
	for p in range(3, n + 1, 2):
		if prime[p]:
			r.append(p)
	return r

def divs(n, start=2):
	r = []
	for i in range(start, int(math.sqrt(n) + 1)):
		if n % i == 0:
			if n / i == i:
				r.append(i)
			else:
				r.extend([i, n // i])
	return r

def divn(n, primes):
	divs_number = 1
	for i in primes:
		if n == 1:
			return divs_number
		t = 1
		while n % i == 0:
			t += 1
			n //= i
		divs_number *= t

def prime(n):
	if n == 2:
		return True
	if n % 2 == 0 or n <= 1:
		return False
	sqr = int(math.sqrt(n)) + 1
	for d in range(3, sqr, 2):
		if n % d == 0:
			return False
	return True

def convn(number, base):
	new_number = 0
	while number > 0:
		new_number += number % base
		number //= base
	return new_number

def cdiv(n, k):
	return n // k + (n % k != 0)

def ispal(s):
	for i in range(len(s) // 2 + 1):
		if s[i] != s[-i - 1]:
			return False
	return True

def function(arr, size, dp):
	if size == 1 or size == 0:
		return 1
	key = ''.join(map(str, arr[:size]))
	if dp[key]:
		return dp[key]
	output = function(arr, size - 1, dp)
	key = ''.join(map(str, arr[:size - 1]))
	dp[key] = output
	if arr[size - 2] * 10 + arr[size - 1] <= 26:
		output += function(arr, size - 2, dp)
		key = ''.join(map(str, arr[:size - 2]))
		dp[key] = output
	return output

def function(arr, s, n, dp):
	if s == 0:
		return 0
	if n == 0 and s != 0:
		return s
	if dp[n][s] != 0:
		return dp[n][s]
	if arr[n - 1] <= s:
		dp[n][s] = max(arr[n - 1], function(arr, s - arr[n - 1], n - 1, dp), function(arr, s, n - 1, dp))
		return dp[n][s]
	else:
		dp[n][s] = function(arr, s, n - 1, dp)
		return dp[n][s]

def main():
	for _ in range(ii()):
		d = {'1': 0, '2': 0, '3': 0}
		s = list(input())
		ans = 200000000
		p0 = 0
		for p1 in range(len(s)):
			d[s[p1]] += 1
			while d['1'] != 0 and d['2'] != 0 and (d['3'] != 0):
				d[s[p0]] -= 1
				ans = min(ans, p1 - p0 + 1)
				p0 += 1
		if p0 == 0 and p1 == len(s) - 1:
			print(0)
		else:
			print(ans)
main()


MOD = 10 ** 9 + 7
RLIMIT = 1000
DEBUG = 1

def main():
	for _ in inputt():
		s = input()
		D = {'1': -inf, '2': -inf, '3': -inf}
		t = inf
		for (i, c) in enumerate(s):
			D[c] = i
			t = min(t, i + 1 - min(D.values()))
		print(t if t != inf else 0)
from math import *
from heapq import *
from itertools import *
from functools import reduce, lru_cache, partial
from collections import Counter, defaultdict, deque
import re, copy, operator, cmath
import sys, io, os, builtins
sys.setrecursionlimit(RLIMIT)
BUFSIZE = 8192

class FastIO(io.IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = io.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(io.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):
	if args:
		sys.stdout.write(str(args[0]))
		split = kwargs.pop('split', ' ')
		for arg in args[1:]:
			sys.stdout.write(split)
			sys.stdout.write(str(arg))
	sys.stdout.write(kwargs.pop('end', '\n'))

def debug(*args, **kwargs):
	if DEBUG and (not __debug__):
		print('debug', *args, **kwargs)
		sys.stdout.flush()
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip()
inputt = lambda t=0: range(t) if t else range(int(input()))
inputs = lambda : input().split()
inputi = lambda k=int: map(k, inputs())
inputl = lambda t=0, k=lambda : list(inputi()): [k() for _ in range(t)] if t else list(k())

def len(a):
	if isinstance(a, range):
		return -((a.start - a.stop) // a.step)
	return builtins.len(a)

def bisect_left(a, x, key=None, lo=0, hi=None):
	if lo < 0:
		lo = 0
	if hi == None:
		hi = len(a)
	if key == None:
		key = do_nothing
	while lo < hi:
		mid = (lo + hi) // 2
		if key(a[mid]) < x:
			lo = mid + 1
		else:
			hi = mid
	return lo

def bisect_right(a, x, key=None, lo=0, hi=None):
	if lo < 0:
		lo = 0
	if hi == None:
		hi = len(a)
	if key == None:
		key = do_nothing
	while lo < hi:
		mid = (lo + hi) // 2
		if x < key(a[mid]):
			hi = mid
		else:
			lo = mid + 1
	return lo

def insort_left(a, x, key=None, lo=0, hi=None):
	lo = bisect_left(a, x, key, lo, hi)
	a.insert(lo, x)

def insort_right(a, x, key=None, lo=0, hi=None):
	lo = bisect_right(a, x, key, lo, hi)
	a.insert(lo, x)
do_nothing = lambda x: x
bisect = bisect_right
insort = insort_right

def index(a, x, default=None, key=None, lo=0, hi=None):
	if lo < 0:
		lo = 0
	if hi == None:
		hi = len(a)
	if key == None:
		key = do_nothing
	i = bisect_left(a, x, key, lo, hi)
	if lo <= i < hi and key(a[i]) == x:
		return a[i]
	if default != None:
		return default
	raise ValueError

def find_lt(a, x, default=None, key=None, lo=0, hi=None):
	if lo < 0:
		lo = 0
	if hi == None:
		hi = len(a)
	i = bisect_left(a, x, key, lo, hi)
	if lo < i <= hi:
		return a[i - 1]
	if default != None:
		return default
	raise ValueError

def find_le(a, x, default=None, key=None, lo=0, hi=None):
	if lo < 0:
		lo = 0
	if hi == None:
		hi = len(a)
	i = bisect_right(a, x, key, lo, hi)
	if lo < i <= hi:
		return a[i - 1]
	if default != None:
		return default
	raise ValueError

def find_gt(a, x, default=None, key=None, lo=0, hi=None):
	if lo < 0:
		lo = 0
	if hi == None:
		hi = len(a)
	i = bisect_right(a, x, key, lo, hi)
	if lo <= i < hi:
		return a[i]
	if default != None:
		return default
	raise ValueError

def find_ge(a, x, default=None, key=None, lo=0, hi=None):
	if lo < 0:
		lo = 0
	if hi == None:
		hi = len(a)
	i = bisect_left(a, x, key, lo, hi)
	if lo <= i < hi:
		return a[i]
	if default != None:
		return default
	raise ValueError

class Tree:

	def __init__(n):
		self._n = n
		self._conn = [[] for _ in range(n)]
		self._list = [0] * n

	def connect(a, b):
		pass

class Sieve:

	def __init__(self):
		self._n = 6
		self._list = [2, 3, 5, 7, 11, 13]

	def extend(self, n):
		if n <= self._list[-1]:
			return
		maxbase = int(n ** 0.5) + 1
		self.extend(maxbase)
		begin = self._list[-1] + 1
		newsieve = [i for i in range(begin, n + 1)]
		for p in self.primerange(2, maxbase):
			for i in range(-begin % p, len(newsieve), p):
				newsieve[i] = 0
		self._list.extend([x for x in newsieve if x])

	def extend_to_no(self, i):
		while len(self._list) < i:
			self.extend(int(self._list[-1] * 1.5))

	def primerange(self, a, b):
		a = max(2, a)
		if a >= b:
			return
		self.extend(b)
		i = self.search(a)[1]
		maxi = len(self._list) + 1
		while i < maxi:
			p = self._list[i - 1]
			if p < b:
				yield p
				i += 1
			else:
				return

	def search(self, n):
		if n < 2:
			raise ValueError
		if n > self._list[-1]:
			self.extend(n)
		b = bisect(self._list, n)
		if self._list[b - 1] == n:
			return (b, b)
		else:
			return (b, b + 1)

	def __contains__(self, n):
		if n < 2:
			raise ValueError
		if not n % 2:
			return n == 2
		(a, b) = self.search(n)
		return a == b

	def __getitem__(self, n):
		if isinstance(n, slice):
			if n.stop:
				self.extend_to_no(n.stop + 1)
				return self._list[n.start:n.stop:n.step]
			return islice(self, n.start, n.stop, n.step)
		else:
			self.extend_to_no(n + 1)
			return self._list[n]
sieve = Sieve()

def isprime(n):
	if n <= sieve._list[-1]:
		return n in sieve
	for i in sieve:
		if not n % i:
			return False
		if n < i * i:
			return True
prime = sieve.__getitem__
primerange = lambda a, b=0: sieve.primerange(a, b) if b else sieve.primerange(2, a)

def factorint(n):
	factors = []
	for i in sieve:
		if n < i * i:
			break
		while not n % i:
			factors.append(i)
			n //= i
	if n != 1:
		factors.append(n)
	return factors
factordict = lambda n: Counter(factorint(n))
main()


def solution():
	t = int(input())
	for _ in range(t):
		s = input()
		index = [0, 0, 0, 0]
		i = 0
		current_max = 0
		seen = set()
		while i < len(s):
			if len(seen) == 2 and (not s[i] in seen):
				if s[i] == '1':
					x = i - min(index[2], index[3]) + 1
					if x < current_max or current_max == 0:
						current_max = x
						if current_max == 3:
							break
				if s[i] == '2':
					x = i - min(index[1], index[3]) + 1
					if x < current_max or current_max == 0:
						current_max = x
						if current_max == 3:
							break
				if s[i] == '3':
					x = i - min(index[1], index[2]) + 1
					if x < current_max or current_max == 0:
						current_max = x
						if current_max == 3:
							break
				seen.clear()
				i -= 1
				continue
			seen.add(s[i])
			index[int(s[i])] = i
			i += 1
		print(current_max)
solution()


import collections
x = int(input())
for _ in range(x):
	s = input()
	n = len(s)
	t = '123'
	need = collections.Counter(t)
	missing = len(t)
	i = I = J = 0
	for (j, c) in enumerate(s, 1):
		missing -= need[c] > 0
		need[c] -= 1
		if not missing:
			while i < j and need[s[i]] < 0:
				need[s[i]] += 1
				i += 1
			if not J or j - i <= J - I:
				(I, J) = (i, j)
	print(len(s[I:J]))


for _ in range(int(input())):
	s = input()
	ll = len(s) - 1
	m = 200001
	(a, b, c) = (-1, -1, -1)
	for i in range(len(s)):
		if s[i] == '1':
			a = i
		elif s[i] == '2':
			b = i
		else:
			c = i
		l = [a, b, c]
		l.sort()
		if m > l[2] - l[0] + 1 and a > -1 and (b > -1) and (c > -1):
			m = l[2] - l[0] + 1
	if m == 200001:
		print(0)
	else:
		print(m)


import sys
input = sys.stdin.readline
for f in range(int(input())):
	s = input()
	n = len(s)
	sol = 0
	l1 = -1
	l2 = -1
	l3 = -1
	for i in range(n):
		if s[i] == '1':
			l1 = i
		if s[i] == '2':
			l2 = i
		if s[i] == '3':
			l3 = i
		if l1 >= 0 and l2 >= 0 and (l3 >= 0):
			l = min(l1, l2)
			l = min(l, l3)
			if sol == 0:
				sol = i - l + 1
			sol = min(sol, i - l + 1)
	print(sol)


from sys import stdin
a = int(stdin.readline())
for b in range(0, a):
	A = stdin.readline()
	temp = A[0]
	count = 0
	uni = 1
	L = set()
	L.add(temp)
	LL = list()
	circ = 0
	if len(A) <= 2:
		print(0)
		continue
	OOO = 0
	for k in A:
		if OOO >= len(A) - 1:
			break
		if k == temp:
			count += 1
		else:
			count += 1
			hold = temp
			temp = k
			L.add(temp)
			if len(L) == 3:
				circ = 1
				LL.append(count)
				count = 2
				L.clear()
				L.add(hold)
				L.add(temp)
			else:
				count = 2
		OOO += 1
	if circ == 0:
		print(0)
	else:
		print(min(LL))


t = int(input())
for i in range(t):
	s = input()
	i = 0
	j = i + 1
	minm = 200005
	state = 1
	while j < len(s):
		if state == 1:
			if s[j] == s[j - 1]:
				i += 1
				j += 1
			else:
				state = 2
				j += 1
		elif state == 2:
			if s[j] == s[j - 1]:
				j += 1
			elif s[j] == s[i]:
				i = j - 1
				j += 1
			else:
				state = 3
		elif state == 3:
			size = j - i + 1
			if size < minm:
				minm = size
			i = j - 1
			j += 1
			state = 2
	if minm == 200005:
		print(0)
	else:
		print(minm)


t = int(input())
for q in range(t):
	ch = input()
	if ch.count('1') * ch.count('2') * ch.count('3') == 0:
		print(0)
	else:
		i = ch.index('1')
		j = ch.index('2')
		k = ch.index('3')
		q = max(i, j, k) - min(i, j, k)
		for a in range(len(ch)):
			if ch[a] == '1':
				i = a
			if ch[a] == '2':
				j = a
			if ch[a] == '3':
				k = a
			q = min(q, max(i, j, k) - min(i, j, k))
		print(q + 1)


for t in range(int(input())):
	n = list(map(int, input()))
	if len(set(n)) < 3:
		print(0)
	else:
		(x, y, z) = (-1, -1, -1)
		ul = 200001
		sum = len(n)
		for i in range(len(n)):
			if n[i] == 1:
				x = i
			elif n[i] == 2:
				y = i
			else:
				z = i
			l = [x, y, z]
			l.sort()
			if ul > l[2] - l[0] + 1 and x > -1 and (y > -1) and (z > -1):
				ul = l[2] - l[0] + 1
		print(ul)


import math
t = int(input())
while t > 0:
	t = t - 1
	string = input()
	booli = {'1': False, '2': False, '3': False}
	curr_length = 0
	min_length = -1
	curr_diff = 0
	for i in range(len(string)):
		if booli[string[i]] == True:
			if string[i] == string[i - 1] and curr_diff > 1:
				curr_length = curr_length + 1
			elif string[i] == string[i - 1] and curr_diff == 1:
				curr_length = 1
			else:
				curr_length = 2
		elif curr_diff == 2:
			curr_length = curr_length + 1
			if min_length == -1 or min_length > curr_length:
				min_length = curr_length
			booli = {'1': False, '2': False, '3': False}
			booli[string[i]] = True
			booli[string[i - 1]] = True
			curr_length = 2
		else:
			booli[string[i]] = True
			curr_diff = curr_diff + 1
			curr_length = curr_length + 1
	print(max(0, min_length))


t = int(input())
for _ in range(t):
	arr = [-1] * 4
	s = list(map(int, list(input())))
	ans = len(s) + 1
	for i in range(len(s)):
		arr[s[i]] = i
		if arr[1] >= 0 and arr[2] >= 0 and (arr[3] >= 0):
			ans = min(ans, max(arr[1:]) - min(arr[1:]) + 1)
	if ans == len(s) + 1:
		ans = 0
	print(ans)


t = int(input())
for i in range(t):
	s = input()
	if '1' in s and '2' in s and ('3' in s):
		if '123' in s or '132' in s or '213' in s or ('231' in s) or ('312' in s) or ('321' in s):
			print(3)
		else:
			l = []
			(a, b, c, d) = (0, 0, 0, 0)
			j = 1
			for i in s:
				if i == '1':
					a = j
				elif i == '2':
					b = j
				else:
					c = j
				if a != 0 and b != 0 and (c != 0):
					l1 = [a, b, c]
					m = max(l1) - min(l1) + 1
					l.append(m)
					if min(l1) == a:
						a = 0
					elif min(l1) == b:
						b = 0
					else:
						c = 0
				j += 1
			print(min(l))
	else:
		print(0)


import math, sys
from sys import stdin, stdout
from collections import Counter, defaultdict, deque
input = stdin.readline
I = lambda : int(input())
li = lambda : list(map(int, input().split()))

def solve():
	s = input().strip()
	(p, q, r) = (-1, -1, -1)
	n = len(s)
	m = 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):
			ma = max(p, q, r)
			mi = min(p, q, r)
			m = min(m, ma - mi + 1)
	if m == n + 1:
		print(0)
	else:
		print(m)
for _ in range(I()):
	solve()


for _ in range(int(input())):
	s = input()
	l = len(s) + 1
	globmin = l
	a = [-1, -1, -1]
	unapp = True
	for ch in s:
		num = int(ch)
		a[num - 1] = 0
		cnt = 0
		for i in range(3):
			x = a[i]
			if x != -1 and num != i + 1:
				a[i] += 1
				cnt += 1
		if unapp and cnt == 2:
			unapp = False
		if unapp == False:
			minm = max(a) + 1
			if minm < globmin:
				globmin = minm
	if globmin == l:
		globmin = 0
	print(globmin)


for _ in range(int(input())):
	s = list(map(int, input()))
	n = len(s)
	l = []
	t = str(s[0])
	for i in range(1, n):
		if s[i] == s[i - 1]:
			t += str(s[i])
		else:
			l.append(t)
			t = str(s[i])
	if len(t) != 0:
		l.append(t)
	m = float('inf')
	for i in range(1, len(l) - 1):
		if l[i - 1][0] != l[i + 1][0]:
			m = min(m, len(l[i]) + 2)
	if m == float('inf'):
		print(0)
	else:
		print(m)


import math
t = int(input())
for _ in range(t):
	x = input()
	n = len(x)
	c = {'1': 0, '2': 0, '3': 0}
	co = 0
	st = 0
	mi = -1
	for j in range(n):
		c[x[j]] += 1
		if c[x[j]] == 1:
			co += 1
		if co == 3:
			while c[x[st]] > 1:
				if c[x[st]] > 1:
					c[x[st]] -= 1
				st += 1
			le = j - st + 1
			if mi == -1 or mi > le:
				mi = le
	if mi == -1:
		print(0)
	else:
		print(mi)


import sys
from bisect import bisect_left as bl
input = sys.stdin.readline
for _ in range(int(input())):
	S = list(map(int, list(input())[:-1]))
	N = len(S)
	table = [[] for _ in range(4)]
	res = N + 1
	for i in range(N):
		table[S[i]].append(i)
	for x in table[1]:
		y = bl(table[2], x)
		if y >= len(table[2]):
			continue
		z = bl(table[3], x)
		if z >= len(table[3]):
			continue
		res = min(res, max(table[2][y], table[3][z]) - x + 1)
	for x in table[2]:
		y = bl(table[1], x)
		if y >= len(table[1]):
			continue
		z = bl(table[3], x)
		if z >= len(table[3]):
			continue
		res = min(res, max(table[1][y], table[3][z]) - x + 1)
	for x in table[3]:
		y = bl(table[1], x)
		if y >= len(table[1]):
			continue
		z = bl(table[2], x)
		if z >= len(table[2]):
			continue
		res = min(res, max(table[1][y], table[2][z]) - x + 1)
	if res < N + 1:
		print(res)
	else:
		print(0)


import os
import sys
from io import BytesIO, IOBase

def main():
	pass
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))
input = lambda : sys.stdin.readline().rstrip('\r\n')
for _ in range(int(input())):
	s = input()
	s = list(map(int, s))
	(a, b, c, l) = (0, 0, 0, [])
	d = {1: 0, 2: 0, 3: 0}
	if len(set(s)) < 3:
		print(0)
	else:
		for (i, j) in enumerate(s, start=1):
			if j == 1:
				d[1] = i
			elif j == 2:
				d[2] = i
			else:
				d[3] = i
			if d[1] > 0 and d[2] > 0 and (d[3] > 0):
				(s1, a) = (0, 0)
				for i in sorted(d.values(), reverse=True):
					a = abs(a - i)
					s1 = s1 + a
					a = i
				l.append(s1 + 1 - max(d.values()))
		print(min(l))


import sys
input = sys.stdin.readline

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

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

def insr():
	s = input().strip()
	return list(s[:len(s)])

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

def from_file(f):
	return f.readline

def solution(S):
	m = float('inf')
	counts = [0] * 3

	def valid():
		return all([c > 0 for c in counts])
	s = 0
	for (k, c) in enumerate(S):
		counts[ord(c) - ord('0') - 1] += 1
		if not valid():
			continue
		staged = ord(S[s]) - ord('0') - 1
		can_remove = counts[staged] > 1
		while can_remove:
			counts[staged] -= 1
			s += 1
			staged = ord(S[s]) - ord('0') - 1
			can_remove = counts[staged] > 1
		m = min(m, k - s + 1)
	return m if m <= len(S) else 0
t = inp()
for _ in range(t):
	S = input().strip()
	print(solution(S))


t = int(input())
for _ in range(t):
	s = input()
	if len(set(s)) != 3:
		print(0)
	else:
		s = [i for i in s]
		q = [0, 0, 0]
		d = 999999999999999999
		for i in range(len(s)):
			if 0 not in q:
				d = min(d, max(q) - min(q))
			q[int(s[i]) - 1] = i + 1
		d = min(d, max(q) - min(q))
		print(d + 1)


from math import inf
import sys
input = lambda : sys.stdin.readline().rstrip()
inp = sys.stdin.buffer.readline

def I():
	return list(map(int, inp().split()))
for _ in range(I()[0]):
	s = input()
	a = [-1, -1, -1]
	cnt = []
	for i in range(len(s)):
		a[int(s[i]) - 1] = i
		cnt.append(a[:])
	ans = 10 ** 7
	for i in cnt:
		if -1 in i:
			continue
		else:
			ans = min(ans, max(i) - min(i) + 1)
	if ans == 10 ** 7:
		ans = 0
	print(ans)


n = int(input())
a = []
for i in range(n):
	s = input()
	m = 0
	e = 0
	d = 0
	t = 0
	s1 = 0
	s2 = 0
	for i in range(len(s)):
		if s[i] == '1':
			e += 1
		elif s[i] == '2':
			d += 1
		else:
			t += 1
		if t != 0 and d != 0 and (e != 0):
			s2 = i
			m = i + 1
			break
	if s2 == 0:
		a.append(0)
	else:
		while True:
			if t > 0 and d > 0 and (e > 0):
				if m > s2 - s1 + 1:
					m = s2 - s1 + 1
				if s[s1] == '1':
					e -= 1
				elif s[s1] == '2':
					d -= 1
				else:
					t -= 1
				s1 += 1
			else:
				s2 += 1
				if s2 > len(s) - 1:
					break
				if s[s2] == '1':
					e += 1
				elif s[s2] == '2':
					d += 1
				else:
					t += 1
		a.append(m)
for i in range(len(a)):
	print(a[i])


for _ in range(int(input())):
	s = input()
	a = []
	n = len(s)
	if s.count('1') == 0 or s.count('2') == 0 or s.count('3') == 0:
		print(0)
		continue
	minn = n
	prev = s[0]
	count = 1
	for i in range(1, n):
		if s[i] == prev:
			count += 1
		else:
			a.append((prev, count))
			count = 1
			prev = s[i]
	a.append((prev, count))
	for i in range(len(a) - 2):
		if a[i][0] != a[i + 1][0] and a[i + 1][0] != a[i + 2][0] and (a[i][0] != a[i + 2][0]):
			minn = min(minn, 2 + a[i + 1][1])
	print(minn)


t = int(input())
for _ in range(t):
	s = input()
	if len(set(s)) != 3:
		print(0)
	else:
		mn = 10 ** 9 + 7
		(a, b, c) = (-1, -1, -1)
		for i in range(len(s)):
			if s[i] == '1':
				a = i
			elif s[i] == '2':
				b = i
			else:
				c = i
			if a != -1 and b != -1 and (c != -1):
				l = max(a, b, c) - min(a, b, c) + 1
				if l < mn:
					mn = l
				if mn == 3:
					break
		print(mn)


from collections import deque
for i in range(int(input())):
	s = input()
	ch = [0 for _ in range(4)]
	ans = 0
	st = deque()
	for j in s:
		num = int(j)
		ch[num] += 1
		st.append(num)
		v = 0
		while ch[1] > 0 and ch[2] > 0 and (ch[3] > 0) and (v == 0):
			b = st[0]
			if ch[b] - 1 > 0:
				ch[st.popleft()] -= 1
			else:
				v = 1
		if ch[1] > 0 and ch[2] > 0 and (ch[3] > 0):
			if len(st) < ans or ans == 0:
				ans = len(st)
	print(ans)


import math
for _ in range(int(input())):
	a = list(input())
	b = [[a[0], 1]]
	for i in range(1, len(a)):
		if len(b) == 0 or b[-1][0] != a[i]:
			b.append([a[i], 1])
		else:
			b[-1][1] += 1
	ans = math.inf
	for i in range(1, len(b) - 1):
		if b[i - 1][0] != b[i + 1][0]:
			ans = min(ans, b[i][1] + 2)
	if ans == math.inf:
		print(0)
	else:
		print(ans)


n = int(input())
for i in range(n):
	dist = 10 ** 21
	f = list(str(input()))
	l = [-1, -1, -1]
	for i in range(len(f)):
		if f[i] == '1':
			l[0] = i
		elif f[i] == '2':
			l[1] = i
		elif f[i] == '3':
			l[2] = i
		if -1 not in l:
			dist = min(dist, max(l) - min(l) + 1)
	if dist > 10 ** 20:
		print(0)
	else:
		print(dist)


import os
import sys
from io import BytesIO, IOBase

def solution(s):
	(i, n) = (0, len(s))
	if n < 3:
		write(0)
		return
	segments = []
	l = 0
	while i < n - 1:
		if s[i] != s[i + 1]:
			segments.append((s[i], (l, i)))
			l = i + 1
		i += 1
	segments.append((s[l], (l, n - 1)))
	ls = len(segments)
	if ls < 3:
		write(0)
		return
	(res, ok) = (float('inf'), False)
	for i in range(ls - 2):
		current = segments[i:i + 3]
		nums = set((x[0] for x in current))
		if len(nums) == 3:
			ok = True
			res = min(res, current[2][1][0] - current[0][1][1] + 1)
	write(res if ok else 0)

def main():
	for _ in range(r_int()):
		s = input()
		solution(s)
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')

def write(*args, end='\n'):
	for x in args[:-1]:
		sys.stdout.write(str(x) + ' ')
	sys.stdout.write(str(args[-1]))
	sys.stdout.write(end)

def r_array():
	return [int(x) for x in input().split()]

def r_int():
	return int(input())
main()


def modinv(n, p):
	return pow(n, p - 2, p)

def main():
	for case in range(int(input())):
		s = input()
		series = [int(x) for x in s]
		count = [0, 0, 0, 0]
		l = 0
		r = 0
		n = len(series)
		count[series[l]] += 1
		min_len = 9999999
		while l < n:
			if count[1] * count[2] * count[3] == 0:
				if r + 1 < n:
					r += 1
					count[series[r]] += 1
				else:
					count[series[l]] -= 1
					l += 1
			else:
				min_len = min(min_len, r - l + 1)
				count[series[l]] -= 1
				l += 1
		if min_len == 9999999:
			print(0)
		else:
			print(min_len)
py2 = round(0.5)
if py2:
	from future_builtins import ascii, filter, hex, map, oct, zip
	range = xrange
import os, sys
from io import IOBase, BytesIO
BUFSIZE = 8192

class FastIO(BytesIO):
	newlines = 0

	def __init__(self, file):
		self._file = file
		self._fd = file.fileno()
		self.writable = 'x' in file.mode or 'w' in file.mode
		self.write = super(FastIO, self).write if self.writable else None

	def _fill(self):
		s = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
		self.seek((self.tell(), self.seek(0, 2), super(FastIO, self).write(s))[0])
		return s

	def read(self):
		while self._fill():
			pass
		return super(FastIO, self).read()

	def readline(self):
		while self.newlines == 0:
			s = self._fill()
			self.newlines = s.count(b'\n') + (not s)
		self.newlines -= 1
		return super(FastIO, self).readline()

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

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		if py2:
			self.write = self.buffer.write
			self.read = self.buffer.read
			self.readline = self.buffer.readline
		else:
			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))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


def shortest_sub(s):
	n = len(s)
	if n < 3:
		return 0
	count = float('inf')
	chars = {'1': 0, '2': 0, '3': 0}
	l = 0
	for r in range(n):
		chars[s[r]] += 1
		while chars[s[l]] > 1:
			chars[s[l]] -= 1
			l += 1
		if chars['1'] and chars['2'] and chars['3']:
			count = min(count, r - l + 1)
	return 0 if count == float('inf') else count
cases = int(input())
for case in range(cases):
	print(shortest_sub(input()))


t = int(input())
for i in range(t):
	s = str(input())
	x = [-1] * 3
	y = int(1000000.0)
	for (i, v) in enumerate(s):
		x[ord(v) - ord('1')] = i
		if min(x) >= 0:
			y = min(y, max(x) - min(x) + 1)
	if y != int(1000000.0):
		print(y)
	else:
		print(0)


for _ in range(int(input())):
	s = input()
	n = len(s)
	p = [-1] * 3
	m = 999999999999999
	for i in range(n):
		if s[i] == '1':
			p[0] = i
		elif s[i] == '2':
			p[1] = i
		else:
			p[2] = i
		if -1 not in p:
			m = min(m, max(p) - min(p) + 1)
	if m == 999999999999999:
		print(0)
	else:
		print(m)


for _ in range(int(input())):
	s = input()
	part_start = -1
	part_end = -1
	part_c = None
	ans = float('inf')
	for i in range(len(s)):
		c = s[i]
		if part_start == -1:
			part_start = i
			part_end = i
			part_c = c
			continue
		if c == part_c:
			part_end += 1
		else:
			if part_start > 0:
				if s[part_start - 1] != c:
					ans = min(ans, part_end - part_start + 3)
			part_start = i
			part_end = i
			part_c = c
	if ans == float('inf'):
		ans = 0
	print(ans)


t = int(input())
while t > 0:
	s = input()
	l = []
	i = 0
	while i < len(s):
		j = i
		while j < len(s) and s[j] == s[i]:
			j += 1
		l.append([s[i], j - i])
		i = j
	i = 0
	mila = False
	ans = 10000000000
	while i + 2 < len(l):
		ss = set()
		ss.add(l[i][0])
		ss.add(l[i + 1][0])
		ss.add(l[i + 2][0])
		if len(ss) == 3:
			mila = True
			ans = min(ans, l[i + 1][1] + 2)
		i += 1
	if mila:
		print(ans)
	else:
		print(0)
	t -= 1


for i in range(int(input())):
	s = input()
	i = j = k = -2
	w = 0
	l = []
	while w < len(s):
		if s[w] == '1':
			i = w
		elif s[w] == '2':
			j = w
		else:
			k = w
		w += 1
		if i >= 0 and j >= 0 and (k >= 0):
			l.append(max(i, j, k) - min(i, j, k) + 1)
	if len(l) == 0:
		print(0)
	else:
		print(min(l))


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()
	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
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):
	(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')
main()


def ck(arr):
	one = None
	two = None
	three = None
	mini = 9999999
	for (i, ele) in enumerate(arr):
		if ele == 1:
			one = i
		elif ele == 2:
			two = i
		elif ele == 3:
			three = i
		if one != None and two != None and (three != None):
			mini = min(max(one, two, three) - min(one, two, three) + 1, mini)
	if mini == 9999999:
		return 0
	return mini
for _ in range(int(input())):
	arr = list(map(int, input()))
	res = ck(arr)
	print(res)


def lastX(s, x):
	res = [-1]
	for i in range(len(s)):
		if s[i] == x:
			res.append(i)
		else:
			res.append(res[-1])
	return res[1:]
for i in range(int(input())):
	s = input()
	(last1, last2, last3) = (lastX(s, '1'), lastX(s, '2'), lastX(s, '3'))
	res = int(1000000000.0)
	for i in range(len(s)):
		y = [last1[i], last2[i], last3[i]]
		if min(y) == -1:
			continue
		res = min(res, max(y) - min(y) + 1)
	if res == 1000000000.0:
		print(0)
	else:
		print(res)


for _ in range(int(input())):
	s = input()
	a = b = c = -1
	ans = 99999999
	for i in range(len(s)):
		if s[i] == '1':
			a = i
		elif s[i] == '2':
			b = i
		else:
			c = i
		if a != -1 and b != -1 and (c != -1):
			ans = min(ans, max(a, b, c) - min(a, b, c))
	if ans != 99999999:
		print(ans + 1)
	else:
		print(0)


from collections import defaultdict
dp = defaultdict(int)
t = int(input())
for _ in range(t):
	s = input()
	dp = {'1': 0, '2': 0, '3': 0}
	i = 0
	ans = 0
	for j in range(len(s)):
		dp[s[j]] += 1
		tf = False
		while all(dp.values()):
			dp[s[i]] -= 1
			i += 1
			tf = True
		if tf:
			if ans == 0:
				ans = j - i + 2
			else:
				ans = min(ans, j - i + 2)
	print(ans)


t = int(input())
for case in range(t):
	s = input()
	n = len(s)
	if n < 3:
		print(0)
	else:
		first_change = 0
		while s[first_change] == s[first_change + 1] and first_change < n - 2:
			first_change += 1
		if first_change == n - 2:
			print(0)
		else:
			ans = n + 1
			(start, mid) = (s[first_change], s[first_change + 1])
			mid_count = 1
			for i in range(first_change + 2, n):
				next = s[i]
				if next == mid:
					mid_count += 1
				elif next == start:
					(mid, start) = (next, mid)
					mid_count = 1
				else:
					ans = min(ans, mid_count + 2)
					(mid, start) = (next, mid)
					mid_count = 1
			if ans == n + 1:
				print(0)
			else:
				print(ans)


for i in range(int(input())):
	st = input()
	hstbl = {}
	j = 0
	ans = 2 ** 31
	while j < len(st):
		if len(hstbl) == 3:
			mini = min(hstbl.values())
			maxi = max(hstbl.values())
			if maxi - mini + 1 < ans:
				ans = maxi - mini + 1
			hstbl[st[j]] = j
		else:
			hstbl[st[j]] = j
		j += 1
	if len(hstbl) == 3:
		mini = min(hstbl.values())
		maxi = max(hstbl.values())
		if maxi - mini + 1 < ans:
			ans = maxi - mini + 1
	if ans == 2 ** 31:
		ans = 0
	print(ans)


def f(a):
	minn = len(a) + 1
	if 1 not in a or 2 not in a or 3 not in a:
		return 0
	for i in range(1, len(a)):
		if a[i] != a[0]:
			break
	l = [[a[0], i - 1], [a[i], i]]
	for i in range(len(a)):
		c = 6 - l[0][0] - l[1][0]
		if a[i] == c:
			minn = min(minn, i - l[0][1] + 1)
			l = [l[1], [c, i]]
		if a[i] == l[0][0]:
			l = [l[1], [a[i], i]]
		if a[i] == l[1][0]:
			l[1][1] = i
	return minn
for tc in range(int(input())):
	a = input()
	b = []
	for i in a:
		b.append(int(i))
	print(f(b))


from sys import stdin, stdout
from math import *
from heapq import *
from collections import *

def main():
	ntest = int(stdin.readline())
	for caseno in range(ntest):
		s = stdin.readline().strip()
		l = 0
		count = {'1': deque(), '2': deque(), '3': deque()}
		mincount = lambda : min([len(dq) for dq in count.values()])
		findleftlen = lambda x: ([len(dq) for dq in count.values() if len(dq) > 0 and dq[0] == x] + [len(s) + 1])[0]
		res = 0
		for (i, c) in enumerate(s):
			count[c].append(i)
			r = i
			while findleftlen(l) > 1:
				for (x, q) in count.items():
					if len(q) > 0:
						if q[0] == l:
							l += 1
							count[x].popleft()
							break
			if mincount() == 1:
				if res == 0:
					res = r - l + 1
				else:
					res = min(res, r - l + 1)
		stdout.write('%d\n' % res)
	return 0
main()


def main():
	n = int(input())
	for i in range(n):
		s = list(input())
		counter = len(s) + 1
		num_one = 0
		num_two = 0
		num_three = 0
		for j in range(len(s)):
			if s[j] == '1':
				num_one = j + 1
			elif s[j] == '2':
				num_two = j + 1
			elif s[j] == '3':
				num_three = j + 1
			if num_one and num_two and num_three and (max(num_three, num_two, num_one) - min(num_three, num_two, num_one) + 1 < counter):
				counter = max(num_three, num_two, num_one) - min(num_three, num_two, num_one) + 1
			if counter == 3:
				break
		if counter < len(s) + 1:
			print(counter)
		else:
			print(0)
main()


import sys
readline = sys.stdin.readline
read = sys.stdin.read
ns = lambda : readline().rstrip()
ni = lambda : int(readline().rstrip())
nm = lambda : map(int, readline().split())
nl = lambda : list(map(int, readline().split()))
prn = lambda x: print(*x, sep='\n')

def solve():
	s = list(map(lambda x: int(x) - 1, list(ns())))
	n = len(s)
	l = [3 * n] * 3
	ans = 3 * n
	for i in range(n - 1, -1, -1):
		l[s[i]] = i
		ans = min(ans, max(l) - i + 1)
	print(ans if ans <= n else 0)
	return
T = ni()
for _ in range(T):
	solve()


t = int(input())
for i in range(t):
	s = input()
	s = list(map(int, s))
	n = len(s)
	counts = [0] * 4
	counts[0] = 1
	inf = 10 ** 8
	ansl = inf
	l = 0
	for r in range(n):
		counts[s[r]] += 1
		while min(counts) > 0:
			if ansl > r - l + 1:
				ansl = r - l + 1
			counts[s[l]] -= 1
			l += 1
	if ansl < inf:
		print(ansl)
	else:
		print(0)


import math
for _ in range(int(input())):
	s = list(input())
	a = 0
	b = 0
	c = 0
	fans = math.inf
	i = 0
	sta = 0
	while i < len(s):
		while i < len(s):
			if a > 0 and b > 0 and (c > 0):
				break
			if s[i] == '1':
				a += 1
			elif s[i] == '2':
				b += 1
			else:
				c += 1
			i += 1
		if a > 0 and b > 0 and (c > 0):
			for j in s[sta:sta + a + b + c]:
				if a == 0 or b == 0 or c == 0:
					break
				if j == '1':
					a -= 1
				elif j == '2':
					b -= 1
				else:
					c -= 1
				sta += 1
			ans = a + b + c + 1
			fans = min(fans, ans)
		else:
			if fans == math.inf:
				fans = 0
			break
	print(fans)


import sys
import math
t = int(sys.stdin.readline())
for i in range(t):
	s = sys.stdin.readline()
	lastone = -1
	lasttwo = -1
	lastthree = -1
	ans = 200000000
	for j in range(len(s)):
		if s[j] == '1':
			if lasttwo > -1 and lastthree > -1:
				ans = min(ans, max(j - lasttwo, j - lastthree))
			lastone = j
		if s[j] == '2':
			if lastone > -1 and lastthree > -1:
				ans = min(ans, max(j - lastone, j - lastthree))
			lasttwo = j
		if s[j] == '3':
			if lasttwo > -1 and lastone > -1:
				ans = min(ans, max(j - lasttwo, j - lastone))
			lastthree = j
	if ans == 200000000:
		print(0)
	else:
		print(ans + 1)


t = int(input())
k = ['1', '2', '3']
for i in range(t):
	f = input()
	f = list(f)
	count = 1
	ans = 1000000
	for i in range(1, len(f)):
		if f[i] == f[i - 1]:
			count += 1
		else:
			if count + 2 < ans:
				if i - count - 1 >= 0 and f[i - count - 1] != f[i]:
					ans = count + 2
			count = 1
	if ans == 1000000:
		print('0')
	else:
		print(ans)


for _ in range(int(input())):
	s = input()
	a = []
	f = 0
	cur = s[0]
	for i in s:
		if i == cur:
			f += 1
		else:
			a.append([cur, f])
			cur = i
			f = 1
	a.append([cur, f])
	if len(a) <= 2:
		print(0)
	else:
		m = 10 ** 10
		for i in range(len(a) - 2):
			if a[i][0] != a[i + 1][1] and a[i][0] != a[i + 2][0]:
				m = min(m, a[i + 1][1] + 2)
		if m == 10 ** 10:
			print(0)
		else:
			print(m)


t = int(input())
for tt in range(t):
	s = input()
	left = 0
	right = 2
	n = len(s)
	m = 10 ** 10
	while left < n and right < n:
		if s[left] == s[left + 1]:
			left += 1
			right += 1
			continue
		if s[right] == s[right - 1]:
			right += 1
			continue
		if s[right] != s[right - 1]:
			if s[right] == s[left]:
				left = right - 1
				right += 1
			else:
				pm = right - left + 1
				if pm < m:
					m = pm
				left = right - 1
				right += 1
	if m == 10 ** 10:
		print(0)
	else:
		print(m)


for _ in range(int(input())):
	st = input()
	if '1' not in st or '2' not in st or '3' not in st:
		print(0)
		continue
	(t1, t2, t3) = (10000000000, 100000000, 10000000)
	nn = len(st)
	for i in range(len(st)):
		if st[i] == '1':
			t1 = i
		if st[i] == '2':
			t2 = i
		if st[i] == '3':
			t3 = i
		if max(t1, t2, t3) - min(t1, t2, t3) < nn:
			nn = max(t1, t2, t3) - min(t1, t2, t3)
	print(nn + 1)


t = int(input())
while t > 0:
	t -= 1
	s = input()
	k = len(s)
	lf1 = -1
	lf2 = -1
	lf3 = -1
	flag = 0
	ans = 10 ** 9 + 7
	for i in range(k):
		if s[i] == '1':
			lf1 = i
		elif s[i] == '2':
			lf2 = i
		elif s[i] == '3':
			lf3 = i
		if lf1 != -1 and lf2 != -1 and (lf3 != -1):
			flag = 1
			temp = max(lf1, lf2, lf3) - min(lf1, lf2, lf3)
			ans = min(ans, temp)
	if flag == 1:
		print(ans + 1)
	else:
		print(0)


t = int(input())
for i in range(0, t):
	s = input()
	k = [0, 0, 0]
	f = [0, 0, 0]
	m = len(s) + 3
	for j in range(0, len(s)):
		d = int(s[j])
		k[d - 1] = 1
		f[d - 1] = j
		if k[0] * k[1] * k[2] == 1:
			ma = max(f) - min(f)
			if ma < m:
				m = ma
	if m == len(s) + 3:
		print(0)
	else:
		print(m + 1)


import sys
from itertools import accumulate

def input():
	return sys.stdin.readline().strip()

def list2d(a, b, c):
	return [[c] * b for i in range(a)]

def list3d(a, b, c, d):
	return [[[d] * c for j in range(b)] for i in range(a)]

def list4d(a, b, c, d, e):
	return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]

def ceil(x, y=1):
	return int(-(-x // y))

def INT():
	return int(input())

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

def LIST(N=None):
	return list(MAP()) if N is None else [INT() for i in range(N)]

def Yes():
	print('Yes')

def No():
	print('No')

def YES():
	print('YES')

def NO():
	print('NO')
INF = 10 ** 18
MOD = 10 ** 9 + 7

def bisearch_min(mn, mx, func):
	ok = mx
	ng = mn
	while ng + 1 < ok:
		mid = (ok + ng) // 2
		if func(mid):
			ok = mid
		else:
			ng = mid
	return ok

def check(m):
	res1 = acc[0][m] - acc[0][i]
	res2 = acc[1][m] - acc[1][i]
	res3 = acc[2][m] - acc[2][i]
	return res1 and res2 and res3
for _ in range(INT()):
	S = input()
	N = len(S)
	acc = list2d(3, N + 1, 0)
	for (i, s) in enumerate(S):
		if s == '1':
			acc[0][i + 1] = 1
		elif s == '2':
			acc[1][i + 1] = 1
		else:
			acc[2][i + 1] = 1
	for s in range(3):
		acc[s] = list(accumulate(acc[s]))
	ans = INF
	for i in range(N):
		res = bisearch_min(i, N + 1, check)
		if res != N + 1:
			ans = min(ans, res - i)
	if ans == INF:
		print(0)
	else:
		print(ans)


import math
t = int(input())
for _ in range(t):
	s = input()
	x = 0
	dic = {}
	n = 1000000000000000000000000
	q = len(s)
	if len(set(s)) != 3:
		print(0)
	else:
		for i in range(q):
			dic[s[i]] = i
			if len(dic) == 3:
				x = int(max(list(dic.values()))) - int(min(list(dic.values())))
				if x + 1 < n:
					n = x + 1
		print(n)


for _ in range(int(input())):
	s = input()
	flag1 = False
	last1 = -1
	flag2 = False
	last2 = -1
	flag3 = False
	last3 = -1
	n = len(s)
	ans = n + 1
	for i in range(n):
		c = s[i]
		if c == '1':
			last1 = i
			flag1 = True
		elif c == '2':
			last2 = i
			flag2 = True
		else:
			last3 = i
			flag3 = True
		if flag1 and flag2 and flag3:
			ans = min(ans, max([last1, last2, last3]) - min([last1, last2, last3]) + 1)
	if ans == n + 1:
		ans = 0
	print(ans)


def solve(s):
	ans = len(s) + 1
	l = 0
	count = [0 for x in range(4)]
	for r in range(len(s)):
		num = int(s[r])
		count[num] += 1
		while count[int(s[l])] > 1:
			count[int(s[l])] -= 1
			l += 1
		if count[1] and count[2] and count[3]:
			ans = min(ans, r - l + 1)
	if ans > len(s):
		return 0
	else:
		return ans
t = int(input())
for _ in range(t):
	s = input()
	print(solve(s))


t = int(input())
for i in range(t):
	ans = 200005
	s = input()
	num1 = -1
	num2 = -1
	num3 = -1
	for j in range(len(s)):
		if s[j] == '1':
			num1 = j
		if s[j] == '2':
			num2 = j
		if s[j] == '3':
			num3 = j
		if num1 != -1 and num2 != -1 and (num3 != -1):
			l = max(num1, max(num2, num3)) - min(num1, min(num2, num3)) + 1
			ans = min(ans, l)
	if ans == 200005:
		print(0)
	else:
		print(ans)


def satisfied(D):
	if D[1] >= 1 and D[2] >= 1 and (D[3] >= 1):
		return 1
	return 0

def minimise(L, R, str1):
	for i in range(L, R + 1):
		e = int(str1[i])
		if D[e] - 1 == 0:
			return i
		else:
			D[e] = D[e] - 1
	return 'g'
for t in range(int(input())):
	arr = []
	str1 = input()
	D = [0, 0, 0, 0]
	L = 0
	for R in range(len(str1)):
		e = int(str1[R])
		D[e] = D[e] + 1
		if satisfied(D) == 1:
			L = minimise(L, R, str1)
			arr.append(R - L + 1)
	if len(arr) == 0:
		print(0)
	else:
		print(min(arr))


no_of_chars = 256

def findSubString(string, pat):
	len1 = len(string)
	len2 = len(pat)
	if len1 < len2:
		print('No such window exists')
		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:
		print('No such window exists')
		return ''
	return string[start_index:start_index + min_len]
for _ in range(int(input())):
	string = input()
	if string.count('1') > 0 and string.count('2') > 0 and (string.count('3') > 0):
		print(len(findSubString(string, '123')))
	else:
		print(0)


MAX = 10 ** 9
for t in range(int(input())):
	s = input()
	ans = MAX
	(i, j, k) = (None, None, None)
	for it in range(len(s)):
		if s[it] == '1':
			i = it
		elif s[it] == '2':
			j = it
		elif s[it] == '3':
			k = it
		if i is not None and j is not None and (k is not None):
			dist = max(abs(i - j), abs(i - k), abs(k - j)) + 1
			ans = min(ans, dist)
	if ans == MAX:
		ans = 0
	print(ans)


for i in range(int(input())):
	stri = input()
	l = [-1] * 3
	m = None
	for i in range(len(stri)):
		l[int(stri[i]) - 1] = i
		if l[0] > -1 and l[1] > -1 and (l[2] > -1):
			if m is None:
				m = max(l) - min(l) + 1
			else:
				m = min(m, max(l) - min(l) + 1)
	print(m) if m else print(0)


import sys, math, os
from io import BytesIO, IOBase
from bisect import bisect_left as bl, bisect_right as br, insort
from collections import defaultdict as dd, deque, Counter

def data():
	return sys.stdin.readline().strip()

def mdata():
	return list(map(int, data().split()))

def outl(var):
	sys.stdout.write(' '.join(map(str, var)) + '\n')

def out(var):
	sys.stdout.write(str(var) + '\n')
sys.setrecursionlimit(100000)
INF = float('inf')
mod = int(1000000000.0) + 7

def main():
	for t in range(int(data())):
		s = data()
		d1 = []
		d2 = []
		d3 = []
		for i in range(len(s)):
			if s[i] == '1':
				d1.append(i)
			elif s[i] == '2':
				d2.append(i)
			else:
				d3.append(i)
		m = INF
		if len(d1) == 0 or len(d2) == 0 or len(d3) == 0:
			print(0)
			continue
		for i in d1:
			k1 = bl(d2, i)
			k2 = bl(d3, i)
			if k1 == len(d2):
				k1 -= 1
			if k2 == len(d3):
				k2 -= 1
			m = min(m, max(d2[k1], d3[k2], i) - min(d2[k1], d3[k2], i) + 1, max(d2[k1 - 1], d3[k2], i) - min(d2[k1 - 1], d3[k2], i) + 1, max(d2[k1], d3[k2 - 1], i) - min(d2[k1], d3[k2 - 1], i) + 1, max(d2[k1 - 1], d3[k2 - 1], i) - min(d2[k1 - 1], d3[k2 - 1], i) + 1)
		print(m)
main()


for u in range(int(input())):
	s = input()
	n = len(s)
	(x, y, z) = (0, 0, 0)
	ka = 10 ** 10
	if '1' not in s or '2' not in s or '3' not in s:
		print(0)
	else:
		for i in range(n):
			if s[i] == '1':
				x = i + 1
			elif s[i] == '2':
				y = i + 1
			else:
				z = i + 1
			if x > 0 and y > 0 and (z > 0):
				m = min(x, y, z)
				mm = max(x, y, z)
				zz = mm - m
				ka = min(ka, zz)
		print(ka + 1)


import sys

def eprint(*args):
	print(*args, file=sys.stderr)
zz = 1
from math import *
import copy
if zz:
	input = sys.stdin.readline
else:
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('all.txt', 'w')

def li():
	return [int(x) for x in input().split()]

def fi():
	return int(input())

def si():
	return list(input().rstrip())

def mi():
	return map(int, input().split())
t = fi()
while t > 0:
	t -= 1
	s = si()
	l = 0
	r = 0
	d = [0 for i in range(4)]
	mini = 10 ** 18
	n = len(s)
	while r < n and l <= r:
		if d[1:].count(0) == 0:
			while l < r and r < n and (d[1:].count(0) == 0):
				mini = min(mini, r - l)
				d[int(s[l])] -= 1
				l += 1
		d[int(s[r])] += 1
		r += 1
	if d[1:].count(0) == 0:
		while l < r and r <= n and (d[1:].count(0) == 0):
			mini = min(mini, r - l)
			d[int(s[l])] -= 1
			l += 1
	print(mini if mini < 10 ** 18 else 0)


import math
from sys import stdin, stdout
from heapq import heapify, heappop, heappush
from collections import Counter, defaultdict
T = int(stdin.readline())
for i in range(T):
	s = stdin.readline()[:-1]
	r = 0
	l = 0
	cnt = defaultdict(int)
	n = len(s)
	ans = float('inf')
	while l < n:
		while r < n and (cnt['1'] == 0 or cnt['2'] == 0 or cnt['3'] == 0):
			cnt[s[r]] += 1
			r += 1
		if cnt['1'] and cnt['2'] and cnt['3']:
			ans = min(ans, r - l)
		cnt[s[l]] -= 1
		l += 1
	if ans == float('inf'):
		print(0)
	else:
		print(ans)


k = 3
t = int(input())
for tt in range(t):
	f = [-1] + list(map(int, input()))
	i = 1
	j = 1
	ib = i
	jb = len(f)
	d = [0 for i in range(k + 1)]
	q = 0
	while j < len(f):
		d[f[j]] += 1
		q += d[f[j]] == 1
		while d[f[i]] > 1:
			d[f[i]] -= 1
			i += 1
		if q == k and j - i < jb - ib:
			jb = j
			ib = i
			if jb - ib == k - 1:
				break
		j += 1
	if q == k:
		print(jb - ib + 1)
	else:
		print(0)


import math
for _ in range(int(input())):
	s = input()
	if s.count('1') == 0 or s.count('2') == 0 or s.count('3') == 0:
		print(0)
	elif s.count('123') or s.count('132') or s.count('213') or s.count('231') or s.count('312') or s.count('321'):
		print(3)
	else:
		a = 2521847451
		b = 2521847478
		c = 1578484854
		ans = 100000000000000000
		for i in range(len(s)):
			if s[i] == '1':
				a = i
			if s[i] == '2':
				b = i
			if s[i] == '3':
				c = i
			if ans > max(a, b, c) - min(a, b, c) + 1:
				ans = max(a, b, c) - min(a, b, c) + 1
		print(ans)


for _ in range(int(input())):
	mii = 10000000
	s = input()
	l1 = []
	l2 = []
	l3 = []
	if s.count('1') == 0 or s.count('2') == 0 or s.count('3') == 0:
		print(0)
	else:
		j = 1
		for i in s:
			if i == '1':
				l1.append(j)
				if len(l1) > 0 and len(l2) > 0 and (len(l3) > 0):
					ma = max(l1[-1], l2[-1], l3[-1])
					mi = min(l1[-1], l2[-1], l3[-1])
					di = ma - mi + 1
					if di < mii:
						mii = di
			elif i == '2':
				l2.append(j)
				if len(l1) > 0 and len(l2) > 0 and (len(l3) > 0):
					ma = max(l1[-1], l2[-1], l3[-1])
					mi = min(l1[-1], l2[-1], l3[-1])
					di = ma - mi + 1
					if di < mii:
						mii = di
			else:
				l3.append(j)
				if len(l1) > 0 and len(l2) > 0 and (len(l3) > 0):
					ma = max(l1[-1], l2[-1], l3[-1])
					mi = min(l1[-1], l2[-1], l3[-1])
					di = ma - mi + 1
					if di < mii:
						mii = di
			j += 1
		if len(l1) > 0 and len(l2) > 0 and (len(l3) > 0):
			print(mii)
		else:
			print(0)


def func(arr):
	one = None
	two = None
	three = None
	mini = 9999999
	for (i, ele) in enumerate(arr):
		if ele == 1:
			one = i
		elif ele == 2:
			two = i
		elif ele == 3:
			three = i
		if one != None and two != None and (three != None):
			mini = min(max(one, two, three) - min(one, two, three) + 1, mini)
	if mini == 9999999:
		return 0
	return mini
n = int(input())
while n:
	num = list(input())
	nums = [int(x) for x in num]
	print(func(nums))
	n -= 1


for _ in range(int(input())):
	s = input()
	n = len(s)
	cnt = [-1] * 3
	m = 10 ** 9
	for i in range(n):
		cnt[int(s[i]) - 1] = i
		if -1 not in cnt:
			m = min(m, max(cnt) - min(cnt) + 1)
	if m == 10 ** 9:
		print(0)
	else:
		print(m)


t = int(input())
for ii in range(t):
	s = input()
	n = len(s)
	l1 = -1
	l2 = -1
	l3 = -1
	ans = 100000000000
	for i in range(n):
		if s[i] == '1':
			l1 = i
		elif s[i] == '2':
			l2 = i
		elif s[i] == '3':
			l3 = i
		if l1 != -1 and l2 != -1 and (l3 != -1):
			ans = min(ans, i - min(l1, l2, l3) + 1)
	if ans != 100000000000:
		print(ans)
	else:
		print(0)


import sys
import math
from math import *
from collections import defaultdict
import os
from io import BytesIO, IOBase
from collections import deque

def main():
	a = b = c = math.inf
	mn = math.inf
	s = input()
	n = len(s)
	for i in range(n):
		if s[i] == '1':
			a = i
			mn = min(mn, sum([abs(i - a), abs(i - b), abs(i - c)]))
		elif s[i] == '2':
			b = i
			mn = min(mn, sum([abs(i - a), abs(i - b), abs(i - c)]))
		else:
			c = i
			mn = min(mn, sum([abs(i - a), abs(i - b), abs(i - c)]))
	if mn == math.inf:
		print(0)
	else:
		print(mn)
for i in range(int(input())):
	main()


for _ in range(int(input())):
	s = input()
	(a, b, c) = (-1, -1, -1)
	ans = 9999999
	for i in range(len(s)):
		if s[i] == '1':
			a = i
		elif s[i] == '2':
			b = i
		elif s[i] == '3':
			c = i
		if a != -1 and b != -1 and (c != -1):
			minn = min(a, b, c)
			maxx = max(a, b, c)
			ans = min(ans, maxx - minn)
	if ans == 9999999:
		print(0)
	else:
		print(ans + 1)


from sys import stdin, stdout, stderr, maxsize
tup = lambda : map(int, stdin.readline().split())
I = lambda : int(stdin.readline())
lint = lambda : [int(x) for x in stdin.readline().split()]
S = lambda : stdin.readline().replace('\n', '').strip()
stpr = lambda x: stdout.write(f'{x}' + '\n')
star = lambda x: print(' '.join(map(str, x)))
for _ in range(I()):
	s = S()
	m = maxsize
	(a, b, c) = (-1, -1, -1)
	for i in range(len(s)):
		if s[i] == '1':
			a = i
		elif s[i] == '2':
			b = i
		elif s[i] == '3':
			c = i
		if a != -1 and b != -1 and (c != -1):
			x = max(a, b, c) - min(a, b, c) + 1
			m = min(m, x)
	print(0) if m == maxsize else print(m)


t = int(input())
for _ in range(t):
	n = input()
	d = dict()
	h = 999992429493
	for i in range(len(n)):
		d[n[i]] = i
		if len(d) == 3:
			a = max(d.values())
			b = min(d.values())
			h = min(h, a - b)
	if h == 999992429493:
		print(0)
	else:
		print(h + 1)


from sys import stdin
input = stdin.readline

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

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

def f(s):
	s = [int(i) - 1 for i in s]
	n = len(s)
	visited = [0, 0, 0]
	start = 0
	start_index = 0
	min_len = 2 ** 32
	count = 0
	curr_count = [0, 0, 0]
	for i in range(n):
		curr_count[s[i]] += 1
		if curr_count[s[i]] == 1:
			count += 1
		if count == 3:
			while curr_count[s[start]] > 1:
				if curr_count[s[start]] > 1:
					curr_count[s[start]] -= 1
				start += 1
			len_window = i - start + 1
			if min_len > len_window:
				min_len = len_window
				start_index = start
	s = s[start_index:start_index + min_len]
	return len(s)
for _ in range(int(input())):
	s = list(input()[:-1])
	if '1' in s and '2' in s and ('3' in s):
		print(f(s))
	else:
		print(0)


from math import factorial as fac
from collections import defaultdict
from copy import deepcopy
import sys, math
f = None
try:
	f = open('q1.input', 'r')
except IOError:
	f = sys.stdin
if 'xrange' in dir(__builtins__):
	range = xrange

def print_case_iterable(case_num, iterable):
	print('Case #{}: {}'.format(case_num, ' '.join(map(str, iterable))))

def print_case_number(case_num, iterable):
	print('Case #{}: {}'.format(case_num, iterable))

def print_iterable(A):
	print(' '.join(A))

def read_int():
	return int(f.readline().strip())

def read_int_array():
	return [int(x) for x in f.readline().strip().split(' ')]

def rns():
	a = [x for x in f.readline().split(' ')]
	return (int(a[0]), a[1].strip())

def read_string():
	return list(f.readline().strip())
NUMBER = 10 ** 9 + 7

def factorial(n):
	M = NUMBER
	f = 1
	for i in range(1, n + 1):
		f = f * i % M
	return f

def mult(a, b):
	return a * b % NUMBER

def minus(a, b):
	return (a - b) % NUMBER

def plus(a, b):
	return (a + b) % NUMBER

def egcd(a, b):
	if a == 0:
		return (b, 0, 1)
	else:
		(g, y, x) = egcd(b % a, a)
		return (g, x - b // a * y, y)

def modinv(a):
	m = NUMBER
	(g, x, y) = egcd(a, m)
	if g != 1:
		raise Exception('modular inverse does not exist')
	else:
		return x % m
from collections import deque, defaultdict
import heapq

def bfs(V, E):
	s = set()
	num_connected_components = 0
	for v in V:
		if v in s:
			continue
		q = deque([])
		s.add(v)
		q.append(v)
		while len(q) > 0:
			x = q.popleft()
			for e in E[x]:
				if e not in s:
					s.add(e)
					q.append(e)
		num_connected_components += 1
	return num_connected_components

def bfs_get_neig(V, get_neig):
	s = set()
	num_connected_components = 0
	for v in V:
		if v in s:
			continue
		q = deque([])
		s.add(v)
		q.append(v)
		while len(q) > 0:
			x = q.popleft()
			for e in get_neig(*x):
				if e not in s:
					s.add(e)
					q.append(e)
		num_connected_components += 1
	return num_connected_components

def binary_count_smaller(L, x):
	l = 0
	if x < L[0]:
		return 0
	r = len(L)
	while r - l > 1:
		mid = (l + r) // 2
		if L[mid] < x:
			l = mid
		else:
			r = mid
	return l + 1

def binary_count_larger(L, x):
	l = 0
	if x > L[-1]:
		return 0
	r = len(L)
	while r - l > 1:
		mid = (l + r) // 2
		if L[mid] <= x:
			l = mid
		else:
			r = mid
	return len(L) - (r - 1)

def regular_bs(L, x, l=None, r=None):
	l = 0 if l == None else l
	r = len(L) if r == None else r
	while r - l > 1:
		m = (r + l) // 2
		l = m if L[m] <= x else l
		r = m if L[m] > x else r
	cnt = 0
	return l
from itertools import product

def preprocess():
	nums = dict(zip(sequences, range(10)))
	changes = defaultdict(dict)
	for comb in map(lambda x: ''.join(x), product(*[['0', '1']] * 7)):
		for seq in sequences:
			a = int(comb, 2)
			b = int(seq, 2)
			num_changes = bin(a ^ b).count('1')
			if num_changes == seq.count('1') - comb.count('1'):
				changes[comb][num_changes] = nums[seq]
	return changes
from collections import deque
from itertools import product

def bi(x):
	return bin(x)[2:]

def check_no_ghg_row(matrix, n, m):
	for i in range(n):
		black = False
		white = False
		for x in matrix[i]:
			if x == '.' and (not black or white):
				continue
			if x == '#' and black and white:
				return False
			if x == '#' and black:
				continue
			if x == '.' and black:
				white = True
			if x == '#':
				black = True
	return True

def check_no_ghg_col(matrix, n, m):
	for j in range(m):
		black = False
		white = False
		for i in range(n):
			x = matrix[i][j]
			if x == '.' and (not black or white):
				continue
			if x == '#' and black and white:
				return False
			if x == '#' and black:
				continue
			if x == '.' and black:
				white = True
			if x == '#':
				black = True
	return True

def empty_col(matrix, n, m):
	for j in range(m):
		empty = True
		for i in range(n):
			if matrix[i][j] == '#':
				empty = False
				break
		if empty:
			return True
	return False

def empty_row(matrix, n, m):
	for i in range(n):
		empty = True
		for j in range(m):
			if matrix[i][j] == '#':
				empty = False
				break
		if empty:
			return True
	return False

def find_lcm(num1, num2):
	if num1 > num2:
		num = num1
		den = num2
	else:
		num = num2
		den = num1
	rem = num % den
	while rem != 0:
		num = den
		den = rem
		rem = num % den
	gcd = den
	lcm = int(int(num1 * num2) / int(gcd))
	return lcm

def find_lcm_array(A):
	if len(A) == 1:
		return A[0]
	lcm = find_lcm(A[0], A[1])
	for i in range(2, len(A)):
		lcm = find_lcm(lcm, A[i])
	return lcm

def solution(s):
	if len(set(s)) < 3:
		return 0
	l = []
	two = set()
	a = s[0]
	i = 0
	while s[i] == a:
		i += 1
	b = s[i]
	l.append(a)
	l.append(b)
	length = 2
	min_length = len(s)
	for j in range(i + 1, len(s)):
		length += 1
		if s[j] not in l:
			min_length = min(min_length, length)
			length = 2
			l[-2] = l[-1]
			l[-1] = s[j]
			continue
		if s[j] == l[-1]:
			continue
		(l[-1], l[-2]) = (l[-2], l[-1])
		length = 2
	return min_length

def main():
	T = read_int()
	for i in range(T):
		s = read_string()
		x = solution(s)
		if 'xrange' not in dir(__builtins__):
			print(x)
		else:
			(print >> output, str(x))
	if 'xrange' in dir(__builtins__):
		print(output.getvalue())
		output.close()
if 'xrange' in dir(__builtins__):
	import cStringIO
	output = cStringIO.StringIO()
main()


from sys import stdin, stdout, maxsize

def get_ternary_string(input_text: str) -> int:
	index = [0] * 3
	count = maxsize
	left = 0
	for right in range(0, len(input_text)):
		pos = ord(input_text[right]) - 49
		index[pos] += 1
		while index[ord(input_text[left]) - 49] > 1:
			index[ord(input_text[left]) - 49] -= 1
			left += 1
		if index[0] != 0 and index[1] != 0 and (index[2] != 0):
			count = min(count, right - left + 1)
	return 0 if count == maxsize else count
test_cases = int(stdin.readline().strip())
while test_cases > 0:
	input_text = stdin.readline().strip()
	print(get_ternary_string(input_text))
	test_cases -= 1


from math import ceil
t = int(input())
for i in range(t):
	x = input()
	L = []
	n = len(x)
	L.append([x[0], 0])
	for i in range(n):
		if x[i] == L[-1][0]:
			L[-1][1] = L[-1][1] + 1
		else:
			L.append([x[i], 1])
	N = len(L)
	R = []
	for i in range(1, N - 1):
		if L[i - 1][0] != L[i + 1][0]:
			R.append(L[i][1] + 2)
	if len(R) == 0:
		print(0)
	else:
		print(min(R))


from collections import Counter, defaultdict, deque
from math import *
import sys
input = sys.stdin.readline

def solve():
	s = input().strip()
	n = len(s)
	c = defaultdict(int)
	p = 0
	rec = 10 ** 6
	for i in range(n):
		c[s[i]] += 1
		ok = False
		while c['1'] > 0 and c['2'] > 0 and (c['3'] > 0):
			c[s[p]] -= 1
			p += 1
			ok = True
		if ok:
			rec = min(rec, c['1'] + c['2'] + c['3'] + 1)
	if rec == 10 ** 6:
		print(0)
	else:
		print(rec)
tt = int(input())
for test in range(tt):
	solve()


from collections import defaultdict
MAX_CHARS = 256

def findSubString(str):
	count = 0
	start = 0
	min_len = float('inf')
	n = len(str)
	dist_count = len(set([x for x in str]))
	curr_count = defaultdict(lambda : 0)
	for j in range(n):
		curr_count[str[j]] += 1
		if curr_count[str[j]] == 1:
			count += 1
		if count == dist_count:
			while curr_count[str[start]] > 1:
				if curr_count[str[start]] > 1:
					curr_count[str[start]] -= 1
				start += 1
			len_window = j - start + 1
			if min_len > len_window:
				min_len = len_window
				start_index = start
	return str[start_index:start_index + min_len]
for i in range(int(input())):
	r = len(findSubString(input()))
	if r < 3:
		print(0)
	else:
		print(r)


for _ in range(int(input())):
	a = list(map(int, input()))
	n = len(a)
	ans = n + 1
	c = [0] * 4
	i = 0
	j = -1
	while i < n:
		c[a[i]] += 1
		while c[a[j + 1]] > 1:
			j += 1
			c[a[j]] -= 1
		if c[1] and c[2] and c[3]:
			ans = min(ans, i - j)
		i += 1
	print(0 if ans > n else ans)


import sys
from collections import Counter
t = int(sys.stdin.readline())
cnt = 0
while cnt < t:
	cnt += 1
	s = sys.stdin.readline().strip('\n')
	n = len(s)
	if len(set(s)) < 3:
		print(0)
		continue
	l = 2
	r = n + 1
	while r - l > 1:
		mid = (r + l) // 2
		check = False
		d = Counter(s[0:mid])
		if d['1'] > 0 and d['2'] > 0 and (d['3'] > 0):
			check = True
		else:
			for i in range(mid, n):
				if s[i] == s[i - mid]:
					continue
				else:
					d[s[i]] += 1
					d[s[i - mid]] -= 1
					if d['1'] > 0 and d['2'] > 0 and (d['3'] > 0):
						check = True
						break
		if check:
			r = mid
		else:
			l = mid
	print(r)


for i in range(int(input())):
	chars = input()
	incr = 0
	max_len = 0
	pos_len = 2000000
	chars_found = {}
	for index in range(1, len(chars)):
		if chars[index - 1] != chars[index]:
			if chars_found.get(chars[index]) is None:
				if chars_found.get(chars[index - 1]) is not None:
					max_len += 1
				else:
					max_len += 2
					incr = 1
				chars_found[chars[index - 1]] = True
				chars_found[chars[index]] = True
				if sum(chars_found.values()) == 3:
					if max_len < pos_len:
						pos_len = max_len
					chars_found = {chars[index]: True, chars[index - 1]: True}
					max_len = 2
			else:
				max_len = 2
		max_len += incr
	if pos_len < 2000000:
		print(pos_len - 1)
	else:
		print(0)


import sys
read = sys.stdin.buffer.read
readlines = sys.stdin.buffer.readlines
t = int(input())
INF = 2 * 10 ** 5 + 1
for case in range(t):
	s = input()
	ans = INF
	pos = [-1, -1, -1]
	idx = 0
	for i in s:
		pos[int(i) - 1] = idx
		if min(pos) != -1:
			ans = min(ans, idx - min(pos))
		idx += 1
	if ans == INF:
		print(0)
	else:
		print(ans + 1)


import math
import sys
input = sys.stdin.readline

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

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

def insr():
	s = input().strip()
	return list(s[:len(s)])

def invr():
	return map(int, input().split())
from collections import defaultdict

def main():
	s = insr()
	g = set(s)
	n = len(s)
	if len(g) == 3:
		d = defaultdict(lambda : -1)
		mn = 200000
		l = set()
		for i in range(n):
			d[int(s[i])] = i
			l.add(s[i])
			if len(l) == 3:
				mn = min(mn, max(d.values()) - min(d.values()) + 1)
		print(mn)
	else:
		print(0)
	return
for _ in range(inp()):
	main()


for _ in range(int(input())):
	s = input()
	l = [0] * 10
	ans = 0
	p1 = 0
	p2 = 0
	le = len(s)
	while p1 <= p2 and p2 <= le:
		if l[1] >= 1 and l[2] >= 1 and (l[3] >= 1):
			l[int(s[p1])] -= 1
			p1 += 1
			ans = min(ans, p2 - p1 + 1)
		else:
			if p2 != le:
				l[int(s[p2])] += 1
				if l[1] >= 1 and l[2] >= 1 and (l[3] >= 1):
					if ans == 0:
						ans = p2 - p1 + 1
					else:
						ans = min(ans, p2 - p1 + 1)
			p2 += 1
	print(ans)


import time

def main():
	start = time.time()
	t = int(input())
	b = []
	for _ in range(t):
		s = input()
		n = len(s)
		c = [0 for i in range(n)]
		d = [0 for i in range(n)]
		e = [0 for i in range(n)]
		for j in range(n):
			if s[j] == '1':
				c[j] = 1
			elif s[j] == '2':
				d[j] = 1
			else:
				e[j] = 1
		c1 = [0] + c
		d1 = [0] + d
		e1 = [0] + e
		for i in range(len(c)):
			c1[i + 1] += c1[i]
			d1[i + 1] += d1[i]
			e1[i + 1] += e1[i]
		if sum(c) == 0 or sum(d) == 0 or sum(e) == 0:
			print(0)
		else:
			ans = float('inf')
			max_l = 0
			for i in range(n):
				if i != n - 1 and s[i] == s[i + 1]:
					continue
				if c1[n] - c1[i] > 0 and d1[n] - d1[i] > 0 and (e1[n] - e1[i] > 0):
					l = max(max_l, i)
					r = min(n, l + ans)
					while r - l > 1:
						m = (r + l) // 2
						if c1[m] - c1[i] > 0 and d1[m] - d1[i] > 0 and (e1[m] - e1[i] > 0):
							r = m
						else:
							l = m
					max_l = max(max_l, l)
					ans = min(ans, r - i)
			print(ans)
	end = time.time()
	print(end - start, file=__import__('sys').stderr)
main()


from sys import stdin
from math import ceil

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

def sinput():
	return input()

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

def linput():
	return list(map(int, stdin.readline().split()))
T = iinput()
while T:
	T -= 1
	s = sinput()
	x = y = z = -len(s) - 1
	ans = len(s)
	if '1' in s and '2' in s and ('3' in s):
		for i in range(len(s)):
			if s[i] == '1':
				x = i
			if s[i] == '2':
				y = i
			if s[i] == '3':
				z = i
			ans = min(ans, i - min(x, y, z) + 1)
		print(ans)
	else:
		print(0)


import sys
t = int(input())
for i in range(t):
	s = input()
	if s.count('1') == 0 or s.count('2') == 0 or s.count('3') == 0:
		print('0')
		continue
	s = list(s)
	prev = s[0]
	pprev = 0
	count = 1
	total = 1
	pos = 0
	mine = sys.maxsize
	for j in range(1, len(s)):
		if s[j] != prev and s[j] != pprev:
			count += 1
			pprev = prev
			prev = s[j]
			total = j - pos
			pos = j
			if count == 3:
				count = 2
				mine = min(mine, total + 2)
				pprev = s[j - 1]
				prev = s[j]
		elif s[j] != prev and s[j] == pprev:
			count = 2
			pprev = prev
			prev = s[j]
			pos = j
	print(mine)


for _ in range(int(input())):
	s = input()
	if len(s) < 3 or s.count('1') == 0 or s.count('2') == 0 or (s.count('2') == 0):
		print(0)
		continue
	d = {'1': 0, '2': 0, '3': 0}
	ans = 0
	n = len(s)
	if len(set(s)) != 3:
		print(0)
		continue
	else:
		l = []
		for i in range(n - 1):
			if s[i] != s[i + 1]:
				l.append(i)
				l.append(i + 1)
		l.append(n - 1)
		l = sorted(list(set(l)))
		j = 0
		ans = 0
		for i in range(1, len(l) - 1):
			if s[l[i]] != s[l[i + 1]]:
				if s[l[i - 1]] != s[l[i + 1]] and s[l[i]] != s[l[i + 1]] and (s[l[i - 1]] != s[l[i]]):
					if ans == 0 or l[i + 1] - l[i - 1] + 1 < ans:
						ans = l[i + 1] - l[i - 1] + 1
			elif i + 2 < len(l):
				if s[l[i - 1]] != s[l[i + 2]] and s[l[i]] != s[l[i + 2]] and (s[l[i - 1]] != s[l[i]]):
					if ans == 0 or l[i + 2] - l[i - 1] + 1 < ans:
						ans = l[i + 2] - l[i - 1] + 1
		print(ans)


for _ in range(int(input())):
	a = list(input())
	ans = 1000000
	(t1, t2, t3) = (-1, -1, -1)
	for i in range(len(a)):
		if a[i] == '1':
			t1 = i
		if a[i] == '2':
			t2 = i
		if a[i] == '3':
			t3 = i
		if t1 != -1 and t2 != -1 and (t3 != -1):
			ans = min(ans, max(abs(t1 - t2), abs(t1 - t3), abs(t2 - t3)) + 1)
	if ans != 1000000:
		print(ans)
	else:
		print(0)


from sys import stdin, stdout
from math import floor, gcd, fabs, factorial, fmod, sqrt, inf, log
from collections import defaultdict as dd, deque
from heapq import merge, heapify, heappop, heappush, nsmallest
from bisect import bisect_left as bl, bisect_right as br, bisect
mod = pow(10, 9) + 7
mod2 = 998244353

def inp():
	return stdin.readline().strip()

def out(var, end='\n'):
	stdout.write(str(var) + '\n')

def outa(*var, end='\n'):
	stdout.write(' '.join(map(str, var)) + end)

def lmp():
	return list(mp())

def mp():
	return map(int, inp().split())

def smp():
	return map(str, inp().split())

def l1d(n, val=0):
	return [val for i in range(n)]

def l2d(n, m, val=0):
	return [l1d(m, val) for j in range(n)]

def remadd(x, y):
	return 1 if x % y else 0

def ceil(a, b):
	return (a + b - 1) // b

def isprime(x):
	if x <= 1:
		return False
	if x in (2, 3):
		return True
	if x % 2 == 0:
		return False
	for i in range(3, int(sqrt(x)) + 1, 2):
		if x % i == 0:
			return False
	return True
for _ in range(int(inp())):
	s = inp()
	ml = []
	(ones, twos, threes) = (-1, -1, -1)
	for i in range(len(s)):
		if s[i] == '1':
			ones = i
		elif s[i] == '2':
			twos = i
		else:
			threes = i
		x = min(ones, twos, threes)
		ml.append(inf if x == -1 else i - x + 1)
	print(min(ml) if min(ml) != inf else 0)


t = int(input())
for i in range(t):
	s = input()
	arr = [-1, -1, -1]
	index = 0
	ans = 10 ** 8
	for i in range(len(s)):
		arr[int(s[i]) - 1] = i + 1
		if -1 not in arr:
			if max(arr) - min(arr) + 1 < ans:
				ans = max(arr) - min(arr) + 1
	if ans != 10 ** 8:
		print(ans)
	else:
		print(0)


t = int(input())
for _ in range(t):
	s = input()
	occ = [0] * 3
	i = 0
	j = 0
	ans = 10 ** 9
	while i < len(s) and j <= len(s):
		if occ[0] >= 1 and occ[1] >= 1 and (occ[2] >= 1):
			ans = min(ans, j - i)
			occ[int(s[i]) - 1] -= 1
			i += 1
		elif j >= len(s):
			break
		else:
			occ[int(s[j]) - 1] += 1
			j += 1
	print(ans if ans < 10 ** 9 else 0)


from sys import stdin, stdout
input = stdin.readline
for _ in range(int(input())):
	arr = input().strip()
	n = len(arr)
	three_arr = [0] * n
	three_arr_rev = [0] * n
	two_arr = [0] * n
	two_arr_rev = [0] * n
	one_arr = [0] * n
	one_arr_rev = [0] * n
	last = -1
	for i in range(n):
		if arr[i] == '3':
			last = i
		three_arr[i] = last
	last = -1
	for i in range(n):
		if arr[i] == '3':
			last = i
		three_arr_rev[i] = last
	last = -1
	for i in range(n):
		if arr[i] == '2':
			last = i
		two_arr[i] = last
	last = -1
	for i in range(n):
		if arr[i] == '2':
			last = i
		two_arr_rev[i] = last
	last = -1
	for i in range(n):
		if arr[i] == '1':
			last = i
		one_arr[i] = last
	last = -1
	for i in range(n):
		if arr[i] == '1':
			last = i
		one_arr_rev[i] = last
	res = 9999999999
	for i in range(n):
		if three_arr[i] != -1:
			a = three_arr[i]
			if two_arr[i] != -1:
				b = two_arr[i]
				if one_arr[i] != -1:
					c = one_arr[i]
					res = min(res, max(a, b, c) - min(a, b, c))
				if one_arr_rev[i] != -1:
					c = one_arr_rev[i]
					res = min(res, max(a, b, c) - min(a, b, c))
			if two_arr_rev[i] != -1:
				b = two_arr_rev[i]
				if one_arr[i] != -1:
					c = one_arr[i]
					res = min(res, max(a, b, c) - min(a, b, c))
				if one_arr_rev[i] != -1:
					c = one_arr_rev[i]
					res = min(res, max(a, b, c) - min(a, b, c))
		if three_arr_rev[i] != -1:
			a = three_arr_rev[i]
			if two_arr[i] != -1:
				b = two_arr[i]
				if one_arr[i] != -1:
					c = one_arr[i]
					res = min(res, max(a, b, c) - min(a, b, c))
				if one_arr_rev[i] != -1:
					c = one_arr_rev[i]
					res = min(res, max(a, b, c) - min(a, b, c))
			if two_arr_rev[i] != -1:
				b = two_arr_rev[i]
				if one_arr[i] != -1:
					c = one_arr[i]
					res = min(res, max(a, b, c) - min(a, b, c))
				if one_arr_rev[i] != -1:
					c = one_arr_rev[i]
					res = min(res, max(a, b, c) - min(a, b, c))
	if res == 9999999999:
		print(0)
	else:
		print(res + 1)


t = int(input())
for i in range(t):
	s = input()
	ans = 2000000
	was = {1: -6000000, 2: -4000000, 3: -2000000}
	for j in range(len(s)):
		was[int(s[j])] = j
		ans = min(ans, max(was.values()) - min(was.values()))
	if ans == 2000000:
		print(0)
	else:
		print(ans + 1)


for t in range(int(input())):
	s = list(map(int, input()))
	num = [0, 0, 0, 0]
	(l, r) = (0, -1)
	min_ = 200001
	while r < len(s) and l < len(s):
		if num[1] and num[2] and num[3]:
			if r - l + 1 < min_:
				min_ = r - l + 1
			num[s[l]] -= 1
			l += 1
		else:
			if r == len(s) - 1:
				break
			r += 1
			num[s[r]] += 1
	if min_ == 200001:
		print(0)
	else:
		print(min_)


import math
t = int(input())
for i in range(t):
	s = input()
	min_length = len(s) + 1
	dic = {}
	dic['1'] = -1
	dic['2'] = -1
	dic['3'] = -1
	for (si, ss) in enumerate(s):
		dic[ss] = si
		if dic['1'] != -1 and dic['2'] != -1 and (dic['3'] != -1):
			min_length = min(min_length, max(dic['1'], dic['2'], dic['3']) - min(dic['1'], dic['2'], dic['3']) + 1)
	if min_length == len(s) + 1:
		print(0)
	else:
		print(min_length)


def solve():
	s = input()
	last_1 = -1
	last_2 = -1
	last_3 = -1
	prev = -1
	ans = 20000000
	for i in range(len(s)):
		if s[i] == '1':
			last_1 = i
			prev = 1
		elif s[i] == '2':
			last_2 = i
			prev = 2
		else:
			last_3 = i
			prev = 3
		if last_3 >= 0 and last_1 >= 0 and (last_2 >= 0):
			if prev == 1:
				maxm = max(last_1 - last_2 + 1, last_1 - last_3 + 1)
				ans = min(ans, maxm)
			elif prev == 2:
				maxm = max(last_2 - last_1 + 1, last_2 - last_3 + 1)
				ans = min(ans, maxm)
			else:
				maxm = max(last_3 - last_2 + 1, last_3 - last_1 + 1)
				ans = min(ans, maxm)
	if ans == 20000000:
		return 0
	return ans
t = int(input())
while t:
	t -= 1
	print(solve())


def solve(s):
	bool1 = False
	bool2 = False
	bool3 = False
	ind1 = -1
	ind2 = -1
	ind3 = -1
	mini = 10 ** 8
	for i in range(len(s)):
		if s[i] == '1':
			bool1 = True
			p1 = i
		elif s[i] == '2':
			bool2 = True
			p2 = i
		elif s[i] == '3':
			bool3 = True
			p3 = i
		if bool1 and bool2 and bool3:
			temp = min(p1, p2, p3)
			if i - temp + 1 < mini:
				mini = i - temp + 1
	if mini == 10 ** 8:
		return 0
	return mini
t = int(input())
for _ in range(t):
	n = input()
	print(solve(n))


t = int(input())
for _ in range(t):
	num = 10000000000
	s = input()
	n = len(s)
	arr = []
	tarr = [num, num, num]
	for i in range(n):
		arr.append(tarr)
	if '3' not in s or '2' not in s or '1' not in s:
		print(0)
		continue
	if s[0] == '1':
		arr[0] = [0, num, num]
	elif s[0] == '2':
		arr[0] = [num, 0, num]
	else:
		arr[0] = [num, num, 0]
	su = 1000000
	for i in range(1, len(s)):
		if s[i] == '1':
			arr[i][0] = 0
			arr[i][1] = arr[i - 1][1] + 1
			arr[i][2] = arr[i - 1][2] + 1
		elif s[i] == '2':
			arr[i][0] = arr[i - 1][0] + 1
			arr[i][1] = 0
			arr[i][2] = arr[i - 1][2] + 1
		else:
			arr[i][0] = arr[i - 1][0] + 1
			arr[i][1] = arr[i - 1][1] + 1
			arr[i][2] = 0
		su = min(su, arr[i][0] + arr[i][1] + arr[i][2])
	print(su)


no_of_chars = 256

def fin(string, pat):
	l1 = len(string)
	l2 = len(pat)
	if l1 < l2:
		print('No such window exists')
		return ''
	hash_pat = [0] * no_of_chars
	hash_str = [0] * no_of_chars
	for i in range(0, l2):
		hash_pat[ord(pat[i])] += 1
	(start, start_index, min_len) = (0, -1, float('inf'))
	count = 0
	for j in range(0, l1):
		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 == l2:
			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 0
	return string[start_index:start_index + min_len]
k = int(input())
while k > 0:
	st = input()
	p = '123'
	if ('1' in st) & ('2' in st) & ('3' in st):
		m = fin(st, p)
		print(len(m))
	else:
		print(0)
	k -= 1


import math
for _ in range(int(input())):
	s = input()
	n = len(s)
	d = {'1': 0, '2': 0, '3': 0}
	i = j = -1
	l = n
	temp = 0
	while i < n - 1 and j < n - 1:
		if d['1'] == 0 or d['2'] == 0 or d['3'] == 0:
			j += 1
			d[s[j]] += 1
		else:
			temp = 1
			while i < n - 1 and d['1'] > 0 and (d['2'] > 0) and (d['3'] > 0):
				l = min(l, j - i)
				i += 1
				d[s[i]] -= 1
	if d['1'] > 0 and d['2'] > 0 and (d['3'] > 0):
		temp = 1
		while i < n - 1 and d['1'] > 0 and (d['2'] > 0) and (d['3'] > 0):
			l = min(l, j - i)
			i += 1
			d[s[i]] -= 1
	if temp == 0 and (d['1'] == 0 or d['2'] == 0 or d['3'] == 0):
		print(0)
		continue
	print(l)


def cnt(i, j, num):
	if num == 1:
		return a[j + 1] - a[i]
	elif num == 2:
		return b[j + 1] - b[i]
	else:
		return c[j + 1] - c[i]
t = int(input())
for _ in range(t):
	s = input()
	n = len(s)
	a = [0 for _ in range(n + 1)]
	b = [0 for _ in range(n + 1)]
	c = [0 for _ in range(n + 1)]
	for i in range(n):
		a[i + 1] = a[i]
		b[i + 1] = b[i]
		c[i + 1] = c[i]
		if s[i] == '1':
			a[i + 1] += 1
		elif s[i] == '2':
			b[i + 1] += 1
		else:
			c[i + 1] += 1
	ans = float('inf')
	for j in range(2, n):
		i = -1
		bb = j - 1
		while bb > 0:
			while i + bb <= j - 2:
				i2 = i + bb
				if cnt(i2, j, 1) > 0 and cnt(i2, j, 2) > 0 and (cnt(i2, j, 3) > 0):
					i += bb
				else:
					break
			bb //= 2
		if i != -1:
			ans = min(ans, j - i + 1)
	if ans == float('inf'):
		ans = 0
	print(ans)


import sys
input = sys.stdin.readline
t = int(input())
li = ['1', '2', '3']
for _ in range(t):
	s = input()
	n = len(s)
	next_ = [[-1] * (n + 1) for i in range(3)]
	for char in range(3):
		for i in range(n)[::-1]:
			next_[char][i] = next_[char][i + 1]
			if s[i] == li[char]:
				next_[char][i] = i
	ans = 10 ** 18
	for i in range(n):
		if min(next_[0][i], next_[1][i], next_[2][i]) == -1:
			continue
		ans = min(max(next_[0][i], next_[1][i], next_[2][i]) - i + 1, ans)
	if ans == 10 ** 18:
		print(0)
	else:
		print(ans)


import sys
import os
import heapq
import math
try:
	path = './file/input.txt'
	if os.path.exists(path):
		sys.stdin = open(path, 'r')
except:
	pass
t = int(input())

def printd(value):
	pass

def case():
	string = input()
	one = -1
	two = -1
	three = -1
	result = len(string) + 1
	for (index, c) in enumerate(string):
		if c == '1':
			one = 0
		elif index > 0 and one >= 0:
			one = one + 1
		if c == '2':
			two = 0
		elif index > 0 and two >= 0:
			two = two + 1
		if c == '3':
			three = 0
		elif index > 0 and three >= 0:
			three = three + 1
		if one >= 0 and two >= 0 and (three >= 0):
			result = min(result, max(one, two, three))
	if result == len(string) + 1:
		result = -1
	print(result + 1)
for _ in range(t):
	case()


T = int(input())
for t in range(T):
	s = input()
	n = len(s)
	c1 = 0
	c2 = -1
	visited = {}
	res = 0
	len_res = 0
	for i in range(n):
		c = s[i]
		r = visited.get(c, 0)
		visited[c] = r + 1
		if r == 0:
			res += 1
			if res == 3:
				c2 = i
				break
	if c2 != -1:
		len_res = c2 - c1 + 1
		for c1 in range(1, n):
			char1 = s[c1 - 1]
			r = visited[char1]
			if r == 1:
				res -= 1
			visited[char1] = r - 1
			if res != 3:
				while c2 < n:
					c2 += 1
					if c2 == n:
						break
					char2 = s[c2]
					r = visited.get(char2, 0)
					visited[char2] = r + 1
					if r == 0:
						res += 1
						if res == 3:
							break
			if c2 == n:
				break
			len_res = min(len_res, c2 - c1 + 1)
	print(len_res)


import sys, os
from io import BytesIO, IOBase
import collections, itertools, bisect, heapq, math, string
BUFSIZE = 8192
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))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def main():
	t = int(input())
	for i in range(t):
		ans = 10 ** 9
		s = str(input())
		cnt = [0] * 4
		l = 0
		for i in range(len(s)):
			temp = ord(s[i]) - ord('0')
			cnt[temp] += 1
			while cnt[1] > 0 and cnt[2] > 0 and (cnt[3] > 0):
				b = ord(s[l]) - ord('0')
				cnt[b] = cnt[b] - 1
				ans = min(ans, i - l + 1)
				l = l + 1
		if ans == 10 ** 9:
			print(0)
		else:
			print(ans)
main()


def solve():
	n = input()
	l = list(n)
	check = [-1, 0, 0, 0]
	for i in range(len(l)):
		check[int(l[i])] += 1
	if check[1] == 0 or check[2] == 0 or check[3] == 0:
		print(0)
	else:
		(i, j) = (0, 0)
		count = [-1, 0, 0, 0]
		ans = len(n)
		while i < len(l) or j < len(l):
			if count[1] > 0 and count[2] > 0 and (count[3] > 0):
				ans = min(ans, j - i)
				count[int(l[i])] -= 1
				i += 1
			elif (count[1] == 0 or count[2] == 0 or count[3] == 0) and j < len(l):
				count[int(l[j])] += 1
				j += 1
			else:
				break
		print(ans)
for _ in range(int(input())):
	solve()


import sys
import heapq
from math import *
import bisect

def input():
	return sys.stdin.readline().strip()

def iinput():
	return int(input())

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

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

def srlinput(fl=False):
	return sorted(list(map(int, input().split())), reverse=fl)

def main():
	s = [int(i) - 1 for i in list(input())]
	n = len(s)
	t = n + 3
	t *= -1
	q = [t for i in range(3)]
	res = 1e+18
	for i in range(n):
		q[s[i]] = i
		res = min(res, i + 1 - min(q))
	if t in q:
		print(0)
	else:
		print(res)
for sdfghjkl in range(iinput()):
	main()


import sys
input = sys.stdin.readline
from collections import *
from bisect import *
t = int(input())
for _ in range(t):
	s = input()[:-1]
	if '1' not in s or '2' not in s or '3' not in s:
		print(0)
		continue
	d = defaultdict(list)
	for i in range(1, 4):
		d[str(i)].append(-10 ** 18)
	for i in range(len(s)):
		d[s[i]].append(i)
	for i in range(1, 4):
		d[str(i)].append(10 ** 18)
	ans = 10 ** 18
	for i in range(len(s)):
		if s[i] == '1':
			idx = bisect_left(d['2'], i)
			l2 = d['2'][idx - 1]
			r2 = d['2'][idx]
			idx = bisect_left(d['3'], i)
			l3 = d['3'][idx - 1]
			r3 = d['3'][idx]
			ans = min(ans, r3 - l2 + 1, r2 - l3 + 1)
		elif s[i] == '2':
			idx = bisect_left(d['1'], i)
			l1 = d['1'][idx - 1]
			r1 = d['1'][idx]
			idx = bisect_left(d['3'], i)
			l3 = d['3'][idx - 1]
			r3 = d['3'][idx]
			ans = min(ans, r3 - l1 + 1, r1 - l3 + 1)
		else:
			idx = bisect_left(d['1'], i)
			l1 = d['1'][idx - 1]
			r1 = d['1'][idx]
			idx = bisect_left(d['2'], i)
			l2 = d['2'][idx - 1]
			r2 = d['2'][idx]
			ans = min(ans, r2 - l1 + 1, r1 - l2 + 1)
	print(ans)


def checkString(string, size):
	aux = {'1': 0, '2': 0, '3': 0}
	for j in range(size):
		aux[string[j]] += 1
	for i in range(len(string) - size):
		if aux['1'] > 0 and aux['2'] > 0 and (aux['3'] > 0):
			return True
		aux[string[i]] -= 1
		aux[string[i + size]] += 1
	if aux['1'] > 0 and aux['2'] > 0 and (aux['3'] > 0):
		return True
	return False
cases = int(input())
for _ in range(cases):
	string = input()
	(l, r) = (0, len(string))
	while l <= r:
		mid = (l + r) // 2
		res = checkString(string, mid)
		if l == r and res:
			l = r + 1
		if res:
			r = mid
		else:
			l = mid + 1
	print(0 if not res else mid)


for _ in range(int(input())):
	s = input()
	freq = {1: 0, 2: 0, 3: 0}
	p1 = 0
	p2 = 0
	ans = float('inf')
	while p2 < len(s):
		freq[int(s[p2])] += 1
		while p1 <= p2 and freq[1] > 0 and (freq[2] > 0) and (freq[3] > 0):
			ans = min(p2 - p1 + 1, ans)
			freq[int(s[p1])] -= 1
			p1 = p1 + 1
		p2 += 1
	if ans == float('inf'):
		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():
			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)


from collections import defaultdict

def findSubString(str):
	count = 0
	start = 0
	start_index = 0
	n = len(str)
	min_len = len(str)
	dist_count = len(set([x for x in str]))
	curr_count = defaultdict(lambda : 0)
	for j in range(n):
		curr_count[str[j]] += 1
		if curr_count[str[j]] == 1:
			count += 1
		if count == dist_count:
			while curr_count[str[start]] > 1:
				if curr_count[str[start]] > 1:
					curr_count[str[start]] -= 1
				start += 1
			len_window = j - start + 1
			if min_len > len_window:
				min_len = len_window
				start_index = start
	return len(str[start_index:start_index + min_len])
for i in range(int(input())):
	s = input()
	if s.count('1') == 0 or s.count('2') == 0 or s.count('3') == 0:
		print(0)
	else:
		print(findSubString(s))


import math
from collections import deque
t = int(input())
rez = []
for i in range(t):
	s = input()
	ss = set()
	for j in s:
		ss.add(j)
	if len(ss) < 3:
		rez.append(0)
		continue
	else:
		a1 = s[0]
		i1 = 0
		a2 = ''
		i2 = -1
		n = len(s)
		ss = set()
		for j in range(len(s)):
			ss.add(s[j])
			if len(ss) == 3:
				n1 = j - i1 + 1
				if n1 < n:
					n = n1
				ss.remove(a1)
				a1 = a2
				a2 = s[j]
				i1 = i2
				i2 = j
			elif s[j] == a1 and a2 == '':
				i1 = j
			elif s[j] != a1 and a2 == '':
				a2 = s[j]
				i2 = j
			elif s[j] == a2:
				i2 = j
			elif s[j] == a1 and a2 != '':
				aa = a2
				a2 = a1
				a1 = aa
				i1 = j - 1
				i2 = j
		rez.append(n)
for i in range(len(rez)):
	print(rez[i])


t = int(input())
for i in range(t):
	f = lambda : map(int, input().split(' '))
	n = input()
	l = len(n)
	li = list(n)
	li = set(li)
	if len(li) < 3:
		print(0)
	else:
		sm = []
		key = []
		c = 1
		f = 0
		for i in range(1, l):
			if n[i] != n[i - 1]:
				sm.append(c)
				f = 1
				c = 1
			else:
				c += 1
				f = 0
		if f == 0:
			sm.append(c)
		for i in range(l - 1):
			if n[i] != n[i + 1]:
				key.append(n[i])
		key.append(n[-1])
		s = [int(key[0]) + int(key[1]) + int(key[2])]
		for i in range(3, len(key)):
			s.append(s[-1] - int(key[i - 3]) + int(key[i]))
		m = 10000000
		for i in range(len(s)):
			if s[i] == 6:
				m = min(m, sm[i + 1])
		print(m + 2)


import sys
input = sys.stdin.readline

def nn():
	return int(input())

def li():
	return list(input())

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

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

def solve_str(s):
	if len(set(s)) == 3:
		ans = len(s)
		indexes = [-1, -1, -1]
		for (i, ch) in enumerate(s):
			indexes[int(ch) - 1] = i
			if all((index >= 0 for index in indexes)):
				ans = min(ans, max(indexes) - min(indexes) + 1)
		print(ans)
	else:
		print(0)
t = nn()
for _ in range(t):
	s = input().strip()
	solve_str(s)


for t in range(int(input())):
	s = input()
	if '1' not in s or '2' not in s or '3' not in s:
		print(0)
		continue
	s_len = len(s)
	ans = float('inf')
	hash_set = {'1': 0, '2': 0, '3': 0}
	j = 0
	for i in range(s_len):
		hash_set[s[i]] += 1
		while hash_set['1'] > 0 and hash_set['2'] > 0 and (hash_set['3'] > 0) and (j < i):
			hash_set[s[j]] -= 1
			ans = min(ans, i - j + 1)
			j += 1
	print(ans)


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)


for s in [*open(0)][1:]:
	i = r = m = 4 ** 9
	a = [-m] * 3
	for d in s[:-1]:
		a[int(d) - 1] = i
		i += 1
		r = min(r, i - min(a))
	print(r % m)


for i in range(int(input())):
	s = input()
	if len(s) < 3:
		print(0)
		continue
	d = []
	l = 1
	seen = set()
	for i in range(len(s) - 1):
		seen.add(s[i])
		if s[i] != s[i + 1]:
			d.append((s[i], l))
			l = 1
		else:
			l += 1
	d.append((s[i + 1], l))
	seen.add(s[i + 1])
	if len(seen) != 3:
		print(0)
		continue
	ml = len(s)
	for i in range(1, len(d) - 1):
		if len(set((d[i][0], d[i - 1][0], d[i + 1][0]))) == 3 and d[i][1] + 2 < ml:
			ml = d[i][1] + 2
	print(ml)


t = int(input())
for _ in range(t):
	s = input()
	if '1' in s and '2' in s and ('3' in s):
		(fv, mv, lv) = ('', '', '')
		md = 0
		ans = len(s)
		for i in range(len(s)):
			if s[i] == '1':
				if fv == '':
					fv = '1'
				elif fv == '1':
					if mv != '':
						fv = mv
						mv = '1'
						md = 1
				elif mv == '':
					mv = '1'
					md = 1
				elif mv == '1':
					md = md + 1
				else:
					lv = '1'
					ans = min(ans, md + 2)
					fv = mv
					mv = lv
					lv = ''
					md = 1
			elif s[i] == '2':
				if fv == '':
					fv = '2'
				elif fv == '2':
					if mv != '':
						fv = mv
						mv = '2'
						md = 1
				elif mv == '':
					mv = '2'
					md = 1
				elif mv == '2':
					md = md + 1
				else:
					lv = '2'
					ans = min(ans, md + 2)
					fv = mv
					mv = lv
					lv = ''
					md = 1
			elif fv == '':
				fv = '3'
			elif fv == '3':
				if mv != '':
					fv = mv
					mv = '3'
					md = 1
			elif mv == '':
				mv = '3'
				md = 1
			elif mv == '3':
				md = md + 1
			else:
				lv = '3'
				ans = min(ans, md + 2)
				fv = mv
				mv = lv
				lv = ''
				md = 1
		print(ans)
	else:
		print(0)


for t in range(int(input())):
	s = [int(c) for c in input()]
	i = 0
	j = 0
	cnt = [0, 0, 0]
	cnt[s[i] - 1] += 1
	if 1 not in s or 2 not in s or 3 not in s:
		print(0)
		continue
	ans = len(s)
	while j < len(s) - 1:
		j += 1
		if s[j] == s[i]:
			i += 1
		else:
			cnt[s[j] - 1] += 1
		while i < j and cnt[s[i] - 1] > 1:
			cnt[s[i] - 1] -= 1
			i += 1
		if min(cnt) > 0:
			ans = min(ans, j - i + 1)
	print(ans)


def sol(s):
	s = list(s)
	dic = {}
	l = 0
	for (i, x) in enumerate(s):
		if x in dic:
			dic[x] = i
		else:
			dic.update({x: i})
		if len(dic) == 3:
			M = max([dic['1'], dic['2'], dic['3']])
			m = min([dic['1'], dic['2'], dic['3']])
			if M - m + 1 == 3:
				return 3
			elif l == 0:
				l = M - m + 1
			else:
				l = min(l, M - m + 1)
	return l
t = int(input())
for _ in range(t):
	s = input()
	v = sol(s)
	print(v)


from collections import defaultdict
MAX_CHARS = 256

def findSubString(str):
	if '1' not in str or '2' not in str or '3' not in str:
		return ''
	n = len(str)
	count = 0
	dist_count = len(set([x for x in str]))
	start = 0
	min_len = 2 * 10 ** 6
	curr_count = defaultdict(lambda : 0)
	for j in range(n):
		curr_count[str[j]] += 1
		if curr_count[str[j]] == 1:
			count += 1
		if count == dist_count:
			while curr_count[str[start]] > 1:
				if curr_count[str[start]] > 1:
					curr_count[str[start]] -= 1
				start += 1
			len_window = j - start + 1
			if min_len > len_window:
				min_len = len_window
				start_index = start
	return str[start_index:start_index + min_len]
t = int(input())
for _ in range(t):
	s = input()
	print(len(findSubString(s)))


for _ in range(int(input())):
	s = input()
	a = [[s[0], 1]]
	for i in range(1, len(s)):
		if s[i] == s[i - 1]:
			a[-1][1] += 1
		else:
			a += ([s[i], 1],)
	ans = len(s) + 1
	for i in range(2, len(a)):
		if not len(set([a[i][0], a[i - 1][0], a[i - 2][0]])) - 3:
			ans = min(ans, 2 + a[i - 1][1])
	print(ans % (len(s) + 1))


import sys
agGK = int(input())
for _ in range(agGK):
	s = str(input())
	a = -1
	b = -1
	c = -1
	minn = len(s) + 1
	for i in range(len(s)):
		if s[i] == '1':
			a = i
		elif s[i] == '2':
			b = i
		elif s[i] == '3':
			c = i
		if a != -1 and b != -1 and (c != -1):
			p = [a, b, c]
			p.sort()
			x = p[0]
			y = p[2]
			z = p[2] - p[0]
			if minn > z:
				minn = z
	if minn == len(s) + 1:
		print(0)
	else:
		print(minn + 1)


import sys
n = int(input())
for num in range(n):
	string = str(input())
	stack1 = []
	stack2 = []
	stack3 = []
	min_len = 2000000
	for index in range(len(string)):
		if string[index] == '1':
			stack1.append(index)
		elif string[index] == '2':
			stack2.append(index)
		else:
			stack3.append(index)
		(l1, l2, l3) = (len(stack1), len(stack2), len(stack3))
		if (l1 != 0) & (l2 != 0) & (l3 != 0):
			curr_len = max(max(stack1[l1 - 1], stack2[l2 - 1]), stack3[l3 - 1]) + 1 - min(min(stack1[l1 - 1], stack2[l2 - 1]), stack3[l3 - 1])
			min_len = min(min_len, curr_len)
	if min_len == 2000000:
		print(0)
	else:
		print(min_len)


def solve(s):
	p1 = -1
	p2 = -1
	p3 = -1
	arr = []
	diff = 200000000
	for i in range(len(s)):
		if s[i] == '1':
			p1 = i
			if p2 != -1 and p3 != -1:
				m = max(p1, p2, p3)
				n = min(p1, p2, p3)
				if m - n < diff:
					diff = m - n
					arr.append(s[n:m + 1])
		elif s[i] == '2':
			p2 = i
			if p1 != -1 and p3 != -1:
				m = max(p1, p2, p3)
				n = min(p1, p2, p3)
				if m - n < diff:
					diff = m - n
					arr.append(s[n:m + 1])
		elif s[i] == '3':
			p3 = i
			if p2 != -1 and p1 != -1:
				m = max(p1, p2, p3)
				n = min(p1, p2, p3)
				if m - n < diff:
					diff = m - n
					arr.append(s[n:m + 1])
	if p1 == -1 or p2 == -1 or p3 == -1:
		return 0
	return len(arr[-1])
t = int(input())
while t > 0:
	s = input()
	ans = solve(s)
	print(ans)
	t -= 1


for __ in range(int(input())):
	s = input()
	n = len(s)
	a = 1000000
	b = 1000000
	c = 1000000
	l = []
	p = []
	j = 0
	for i in range(n):
		if s[i] == '1':
			a = i
			if i == j:
				h = a
		elif s[i] == '2':
			b = i
			if i == j:
				h = b
		else:
			c = i
			if i == j:
				h = c
		if a != 1000000 and b != 1000000 and (c != 1000000):
			p.append(a)
			p.append(b)
			p.append(c)
			p.sort()
			x = p[len(p) - 1] - p[0] + 1
			if x == 3:
				l.append(x)
				break
			l.append(x)
			if h == a:
				a = 1000000
			if h == b:
				b = 1000000
			if h == a:
				b = 1000000
			p.clear()
	if len(l) == 0:
		print(0)
	else:
		print(min(l))


no_of_chars = 256

def func(string, pat):
	len1 = len(string)
	len2 = 3
	if len1 < len2:
		print(0)
		return
	hp = [0] * no_of_chars
	hs = [0] * no_of_chars
	for i in range(0, len2):
		hp[ord(pat[i])] += 1
	(start, start_index, min_len) = (0, -1, float('inf'))
	count = 0
	for j in range(0, len1):
		hs[ord(string[j])] += 1
		if hp[ord(string[j])] != 0 and hs[ord(string[j])] <= hp[ord(string[j])]:
			count += 1
		if count == len2:
			while hs[ord(string[start])] > hp[ord(string[start])] or hp[ord(string[start])] == 0:
				if hs[ord(string[start])] > hp[ord(string[start])]:
					hs[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:
		print(0)
		return
	print(len(string[start_index:start_index + min_len]))
t = int(input())
for z in range(t):
	s = input()
	func(s, '123')


def main():
	for _ in range(int(input())):
		a = str(input())
		lst = [-1, -1, -1]
		key = [0, 0]
		mn = 1000000000
		for j in range(len(a)):
			i = int(a[j])
			lst[i - 1] = j
			temp = key[0]
			if i == key[1] or key[1] == 0:
				key[1] = i
				continue
			if i == key[0] or key[0] == 0:
				key[0] = key[1]
				key[1] = i
			else:
				key[0] = key[1]
				key[1] = i
				mn1 = max(lst) - min(lst) + 1
				if mn1 < mn:
					mn = mn1
		if mn == 1000000000:
			print(0)
		else:
			print(mn)
main()


from math import *
t = int(input())
for _ in range(t):
	a = input()
	c = dict()
	ans = 10 ** 10
	j = 0
	for i in range(len(a)):
		if a[i] not in c:
			c[a[i]] = 1
		else:
			c[a[i]] += 1
		while j < i:
			if c[a[j]] > 1:
				c[a[j]] -= 1
				j += 1
			else:
				break
		if '1' in c and '2' in c and ('3' in c):
			if c['1'] >= 1 and c['2'] >= 1 and (c['3'] >= 1):
				ans = min(ans, i - j + 1)
	if ans == 10 ** 10:
		print(0)
	else:
		print(ans)


def isvalid(s):
	count1 = 0
	count2 = 0
	count3 = 0
	for i in s:
		if i == '1':
			count1 += 1
		elif i == '2':
			count2 += 1
		else:
			count3 += 1
	if count1 == 0 or count2 == 0 or count3 == 0:
		return 0
	return 1
t = int(input())
for you in range(t):
	s = input()
	if isvalid(s) == 0:
		print(0)
	else:
		start = 0
		end = 0
		i = 0
		lfi = []
		n = len(s)
		while i < n:
			if s[i] == s[start]:
				while s[i] == s[start]:
					if i != 0:
						end += 1
					i += 1
					if i == n:
						break
			else:
				lfi.append((s[i - 1], end - start + 1))
				start = i
				end = start
				i += 1
		lfi.append((s[-1], end - start + 1))
		lma = []
		for i in range(len(lfi) - 2):
			if lfi[i][0] != lfi[i + 2][0]:
				lma.append(2 + lfi[i + 1][1])
		print(min(lma))


def check(dic):
	if dic['1'] > 0 and dic['2'] > 0 and (dic['3'] > 0):
		return True
	return False
from collections import defaultdict
for ii in range(int(input())):
	s = input()
	left = 0
	count = defaultdict(int)
	count['1'] = 0
	count['3'] = 0
	count['2'] = 0
	ans = 10 ** 10
	for i in range(len(s)):
		f = 0
		count[s[i]] += 1
		while check(count):
			count[s[left]] -= 1
			left += 1
			f = 1
		k = i - (left - 1) + 1
		if k >= 3 and f:
			ans = min(ans, k)
	if ans == 10 ** 10:
		print(0)
	else:
		print(ans)


import sys
input = sys.stdin.readline
(T,) = map(int, input().split())
for t in range(T):
	s = input().strip()
	N = len(s)
	dp = [[0] * (N + 1) for _ in range(3)]
	for i in range(N):
		c = int(s[i])
		for j in range(3):
			dp[j][i + 1] = dp[j][i] + (1 if j == c - 1 else 0)
	R = [10 ** 9] * (N + 1)
	l = [0] * 3
	for r in range(1, N + 1):
		tmp = 0
		for j in range(3):
			if dp[j][r] == 0:
				tmp = 1
		if tmp:
			continue
		for j in range(3):
			dpj = dp[j]
			dpr = dpj[r]
			while dpr != dpj[l[j]]:
				l[j] += 1
		R[r] = r - min(l)
	rr = min(R) + 1
	if rr >= 10 ** 9:
		print(0)
	else:
		print(rr)


import sys
input = sys.stdin.readline
from math import log2, log, ceil

def swaparr(arr, a, b):
	temp = arr[a]
	arr[a] = arr[b]
	arr[b] = temp

def gcd(a, b):
	if a == 0:
		return b
	return gcd(b % a, a)

def nCr(n, k):
	if k > n - k:
		k = n - k
	res = 1
	for i in range(k):
		res = res * (n - i)
		res = res / (i + 1)
	return res

def upper_bound(a, x, lo=0):
	hi = len(a)
	while lo < hi:
		mid = (lo + hi) // 2
		if a[mid] < x:
			lo = mid + 1
		else:
			hi = mid
	return lo

def primefs(n):
	primes = {}
	while n % 2 == 0:
		primes[2] = primes.get(2, 0) + 1
		n = n // 2
	for i in range(3, int(n ** 0.5) + 2, 2):
		while n % i == 0:
			primes[i] = primes.get(i, 0) + 1
			n = n // i
	if n > 2:
		primes[n] = primes.get(n, 0) + 1
	return primes

def power(x, y, p):
	res = 1
	x = x % p
	if x == 0:
		return 0
	while y > 0:
		if y & 1 == 1:
			res = res * x % p
		y = y >> 1
		x = x * x % p
	return res

def swap(a, b):
	temp = a
	a = b
	b = temp
	return (a, b)

def find(x, link):
	p = x
	while p != link[p]:
		p = link[p]
	while x != p:
		nex = link[x]
		link[x] = p
		x = nex
	return p

def union(x, y, link, size):
	x = find(x, link)
	y = find(y, link)
	if size[x] < size[y]:
		(x, y) = swap(x, y)
	if x != y:
		size[x] += size[y]
		link[y] = x

def sieve(n):
	prime = [True for i in range(n + 1)]
	p = 2
	while p * p <= n:
		if prime[p] == True:
			for i in range(p * p, n + 1, p):
				prime[i] = False
		p += 1
	return prime
MAXN = int(1000000.0 + 5)

def spf_sieve():
	spf[1] = 1
	for i in range(2, MAXN):
		spf[i] = i
	for i in range(4, MAXN, 2):
		spf[i] = 2
	for i in range(3, ceil(MAXN ** 0.5), 2):
		if spf[i] == i:
			for j in range(i * i, MAXN, i):
				if spf[j] == j:
					spf[j] = i
spf = [0 for i in range(MAXN)]
spf_sieve()

def factoriazation(x):
	ret = {}
	while x != 1:
		ret[spf[x]] = ret.get(spf[x], 0) + 1
		x = x // spf[x]
	return ret

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

def str_array():
	return input().strip().split()
MOD = int(1000000000.0) + 7
CMOD = 998244353
INF = float('inf')
NINF = -float('inf')
for _ in range(int(input())):
	string = input().strip()
	n = len(string)
	if '1' not in string or '2' not in string or '3' not in string:
		print(0)
	else:
		one = []
		two = []
		three = []
		ans = INF
		for i in range(n):
			if string[i] == '1':
				one.append(i)
			elif string[i] == '2':
				two.append(i)
			else:
				three.append(i)
		i = j = k = 0
		while i < len(one) and j < len(two) and (k < len(three)):
			mini = min(one[i], two[j], three[k])
			maxi = max(one[i], two[j], three[k])
			ans = min(ans, maxi - mini + 1)
			arr = [one[i], two[j], three[k]]
			ind = arr.index(min(arr))
			if ind == 0:
				i += 1
			elif ind == 1:
				j += 1
			else:
				k += 1
		print(ans)


def findMinLenStr(str, k):
	n = len(str)
	st = 0
	end = 0
	cnt = [0] * 26
	distEle = 0
	currlen = 0
	minlen = n + 1
	startInd = -1
	while end < n:
		cnt[ord(str[end]) - ord('0')] += 1
		if cnt[ord(str[end]) - ord('0')] == 1:
			distEle += 1
		if distEle > k:
			while st < end and distEle > k:
				if cnt[ord(str[st]) - ord('0')] == 1:
					distEle -= 1
				cnt[ord(str[st]) - ord('0')] -= 1
				st += 1
		if distEle == k:
			while st < end and cnt[ord(str[st]) - ord('0')] > 1:
				cnt[ord(str[st]) - ord('0')] -= 1
				st += 1
			currlen = end - st + 1
			if currlen < minlen:
				minlen = currlen
				startInd = st
		end += 1
	if minlen == n + 1:
		return 0
	else:
		return minlen
for _ in range(int(input())):
	str = input()
	k = 3
	print(findMinLenStr(str, k))


for _ in range(int(input())):
	num = str(input())
	l = len(num)
	d = [-1] * 3
	m = 1000000000.0
	for i in range(l):
		d[int(num[i]) - 1] = i
		if -1 not in d:
			m = min(m, max(d) - min(d) + 1)
	if m is 1000000000.0:
		print(0)
	else:
		print(m)


t = int(input())
for i1 in range(t):
	s = [int(i) for i in input()]
	pointer = [0, 0]
	advance = 1
	result = len(s) + 1
	if len(set(s)) < 3:
		print(0)
		continue
	c = [0, 0, 0, 0]
	c[s[0]] += 1
	while True:
		if c[1] > 0 and c[2] > 0 and (c[3] > 0):
			if result > pointer[1] - pointer[0] + 1:
				result = pointer[1] - pointer[0] + 1
			advance = 0
		else:
			advance = 1
		if advance == 1 and pointer[1] >= len(s) - 1:
			break
		if advance == 1:
			pointer[1] += 1
			c[s[pointer[1]]] += 1
		else:
			c[s[pointer[0]]] -= 1
			pointer[0] += 1
	print(result)


t = int(input())
while t:
	t = t - 1
	s = input()
	se = set(s)
	if len(se) < 3:
		print(0)
		continue
	a1 = -1
	a2 = -1
	a3 = -1
	out = len(s)
	for i in range(len(s)):
		if s[i] == '1':
			a1 = i
		elif s[i] == '2':
			a2 = i
		elif s[i] == '3':
			a3 = i
		if a1 != -1 and a2 != -1 and (a3 != -1):
			out = min(out, max(a1, max(a2, a3)) - min(a1, min(a2, a3)) + 1)
	print(out)


from fractions import Fraction
import bisect
import os
from collections import Counter
import bisect
from collections import defaultdict
import math
import random
import heapq as hq
from math import sqrt
import sys
from functools import reduce, cmp_to_key
from collections import deque
import threading
from itertools import combinations
from io import BytesIO, IOBase
from itertools import accumulate

def input():
	return sys.stdin.readline().strip()

def iinput():
	return int(input())

def tinput():
	return input().split()

def rinput():
	return map(int, tinput())

def rlinput():
	return list(rinput())

def factors(n):
	return set(reduce(list.__add__, ([i, n // i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0)))
for _ in range(iinput()):
	s = input()
	n = len(s)
	o = -1
	t = -1
	thr = -1
	ans = float('inf')
	for i in range(n):
		if s[i] == '1':
			o = i
		elif s[i] == '2':
			t = i
		else:
			thr = i
		if o != -1 and t != -1 and (thr != -1):
			ans = min(ans, max(o, t, thr) - min(o, t, thr))
	print([ans + 1, 0][ans == float('inf')])


import math

def read_int():
	return int(input().strip())

def read_ints():
	return list(map(int, input().strip().split(' ')))

def solve():
	s = input().strip()
	G = {}
	min_length = math.inf
	for (i, c) in enumerate(s):
		G[c] = i
		if len(G) == 3:
			min_length = min(min_length, i - min(G.values()) + 1)
	if min_length == math.inf:
		return 0
	return min_length
T = read_int()
for _ in range(T):
	print(solve())


import sys
import math

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

def IL():
	return list(map(int, sys.stdin.readline().strip().split()))
t = I()
for tt in range(t):
	s = sys.stdin.readline().strip()
	st = 0
	en = 0
	d = {1: 0, 2: 0, 3: 0}
	d[int(s[st])] += 1
	res = 0
	while en < len(s):
		if st <= en and d[1] > 0 and (d[2] > 0) and (d[3] > 0):
			if res == 0:
				res = en - st + 1
			else:
				res = min(res, en - st + 1)
			d[int(s[st])] -= 1
			st += 1
		else:
			en += 1
			if en < len(s):
				d[int(s[en])] += 1
	if st <= en and d[1] > 0 and (d[2] > 0) and (d[3] > 0):
		if res == 0:
			res = en - st + 1
		else:
			res = min(res, en - st + 1)
		d[int(s[st])] -= 1
		st += 1
	print(res)


import collections

def solve(s, t):
	need = collections.Counter(t)
	missing = len(t)
	(start, end) = (0, 0)
	i = 0
	for (j, char) in enumerate(s, 1):
		if need[char] > 0:
			missing -= 1
		need[char] -= 1
		if missing == 0:
			while i < j and need[s[i]] < 0:
				need[s[i]] += 1
				i += 1
			need[s[i]] += 1
			missing += 1
			if end == 0 or j - i < end - start:
				(start, end) = (i, j)
			i += 1
	if start == end:
		return 0
	return end - start
t = int(input())
for _ in range(t):
	s = input()
	print(solve(s, '123'))


n = int(input())
for i in range(n):
	s = input()
	l = -1
	r = -1
	c = [0] * 3
	mas = []
	while r < len(s) - 1:
		if c[0] == 0 or c[1] == 0 or c[2] == 0:
			r += 1
			c[int(s[r]) - 1] += 1
		else:
			l += 1
			c[int(s[l]) - 1] -= 1
			if c[0] == 0 or c[1] == 0 or c[2] == 0:
				mas += [c[0] + c[1] + c[2] + 1]
	if c[0] != 0 and c[1] != 0 and (c[2] != 0):
		while c[0] * c[1] * c[2] != 0:
			l += 1
			c[int(s[l]) - 1] -= 1
		mas += [c[0] + c[1] + c[2] + 1]
	if len(mas) == 0:
		print(0)
	else:
		print(min(mas))


t = int(input())
for _ in range(t):
	st = list((int(x) for x in input()))
	lis = [0, 0, 0, 0]
	le = 10000000000
	max1 = -1
	max2 = -1
	max3 = -1
	for i in range(len(st)):
		lis[st[i]] += 1
		if st[i] == 1:
			max1 = i
		if st[i] == 2:
			max2 = i
		if st[i] == 3:
			max3 = i
		li = [max1, max2, max3]
		a = max(li)
		b = min(li)
		if lis[1] * lis[2] * lis[3] > 0:
			le = min(le, a - b + 1)
	if le == 10000000000:
		print(0)
	else:
		print(le)


def f(s):
	ans = 300000
	ind = 0
	a = 0
	n = len(s)
	while a < n - 2 and s[a] == s[a + 1]:
		a += 1
	b = a + 1
	while a < n - 2 and b < n - 1:
		while b < n - 1 and s[b] == s[b + 1]:
			b += 1
		if b < n - 1 and s[a] != s[b + 1]:
			ans = min(ans, b + 2 - a)
			ind = 1
		a = b
		b = a + 1
	if ind == 0:
		return 0
	else:
		return ans
t = int(input())
for i in range(t):
	print(f(input()))


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)


def main(s):
	ans = float('inf')
	i = 0
	n = len(s)
	cnt = [0, 0, 0]
	st = set()
	for j in range(n):
		cnt[int(s[j]) - 1] += 1
		st.add(s[j])
		if len(st) == 3:
			while i < j and len(st) == 3 and (cnt[int(s[i]) - 1] > 0):
				ans = min(ans, j - i + 1)
				cnt[int(s[i]) - 1] -= 1
				if cnt[int(s[i]) - 1] == 0:
					st.remove(s[i])
				i += 1
	return ans if ans != float('inf') else 0
n = int(input())
nums = [input() for _ in range(n)]
for num in nums:
	print(main(num))


for _ in range(int(input())):
	q = input()
	w = [-len(q), -len(q), -len(q)]
	ans = len(q)
	for i in range(len(q)):
		w[int(q[i]) - 1] = i
		ans = min(max(w) - min(w), ans)
	if -len(q) in w:
		print(0)
	else:
		print(ans + 1)


n = int(input())
a = []
b = []
lst1 = []
lst2 = [0 for x in range(n)]
for i in range(n):
	lst2[i] = input()
for lst in lst2:
	a = []
	b = []
	for j in range(len(lst) - 1):
		if j == 0:
			a.append(lst[j])
			b.append(1)
		if lst[j] == lst[j + 1]:
			b[len(b) - 1] += 1
		if lst[j] != lst[j + 1]:
			a.append(lst[j + 1])
			b.append(1)
	kaiguan = 0
	min_ = 200010
	for j in range(1, len(a) - 1):
		if a[j] != a[j - 1] and a[j] != a[j + 1] and (a[j - 1] != a[j + 1]) and (b[j] + 2 < min_):
			min_ = b[j] + 2
			kaiguan = 1
	if kaiguan == 1:
		lst1.append(min_)
	else:
		lst1.append(0)
for i in range(n):
	print(lst1[i])


def f(string, pat):
	len1 = len(string)
	len2 = len(pat)
	if len1 < len2:
		return ''
	hash_pat = [0] * 3
	hash_str = [0] * 3
	for i in range(0, len2):
		hash_pat[int(pat[i]) - 1] += 1
	(start, start_index, min_len) = (0, -1, float('inf'))
	count = 0
	for j in range(0, len1):
		hash_str[int(string[j]) - 1] += 1
		if hash_pat[int(string[j]) - 1] != 0 and hash_str[int(string[j]) - 1] <= hash_pat[int(string[j]) - 1]:
			count += 1
		if count == len2:
			while hash_str[int(string[start]) - 1] > hash_pat[int(string[start]) - 1] or hash_pat[int(string[start]) - 1] == 0:
				if hash_str[int(string[start]) - 1] > hash_pat[int(string[start]) - 1]:
					hash_str[int(string[start]) - 1] -= 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 _ in range(int(input())):
	s = input()
	p = '123'
	ans = f(s, p)
	print(len(ans))


t = int(input())
for i in range(t):
	s = input()
	s += s[-1]
	c = set()
	foo = set()
	l = []
	ind = 0
	for i in s:
		foo.add(i)
	if len(foo) != 3:
		print(0)
		continue
	for i in range(len(s) - 1):
		if s[i] != s[i + 1] and len(c) == 0:
			c.add(s[i])
			c.add(s[i + 1])
			ind = i
		if s[i] != s[i + 1] and len(c) == 2:
			c.add(s[i + 1])
			if len(c) == 3:
				l.append(i + 2 - ind)
				c = set()
				c.add(s[i])
				c.add(s[i + 1])
			ind = i
	print(min(l))


def read_int():
	return int(input())

def read_ints():
	return list(map(int, input().split(' ')))
t = read_int()
for case_num in range(t):
	s = input()
	cnt = dict()
	cnt['1'] = 0
	cnt['2'] = 0
	cnt['3'] = 0
	ans = len(s) + 1
	l = 0
	r = -1
	while r < len(s):
		while cnt['1'] == 0 or cnt['2'] == 0 or cnt['3'] == 0:
			r += 1
			if r >= len(s):
				break
			cnt[s[r]] += 1
		if cnt['1'] > 0 and cnt['2'] > 0 and (cnt['3'] > 0):
			ans = min(ans, r - l + 1)
		cnt[s[l]] -= 1
		l += 1
	print(ans if ans <= len(s) else 0)


from collections import defaultdict

def minRange(arr, n, k):
	(l, r) = (0, n)
	i = 0
	j = -1
	hm = defaultdict(lambda : 0)
	while i < n:
		while j < n:
			j += 1
			if len(hm) < k and j < n:
				hm[arr[j]] += 1
			if len(hm) == k and r - l >= j - i:
				(l, r) = (i, j)
				break
			if len(hm) == k:
				break
		if len(hm) < k:
			break
		while len(hm) == k:
			if hm[arr[i]] == 1:
				del hm[arr[i]]
			else:
				hm[arr[i]] -= 1
			i += 1
			if len(hm) == k and r - l >= j - i:
				(l, r) = (i, j)
		if hm[arr[i]] == 1:
			del hm[arr[i]]
		else:
			hm[arr[i]] -= 1
		i += 1
	if l == 0 and r == n:
		return 0
	else:
		return r - l + 1
for i in range(int(input())):
	a = input()
	arr = []
	m = len(a)
	for i in range(m):
		arr += [int(a[i])]
	if m >= 3:
		if set(arr) == {1, 2, 3}:
			print(minRange(arr, m, 3))
		else:
			print(0)
	else:
		print(0)


testcases = int(input())
for i in range(testcases):
	s = input()
	change = 0
	first = -1
	last = -1
	i = 0
	flag = 0
	maximum = len(s)
	if len(s) > 2:
		while i + 1 < len(s):
			if s[i] != s[i + 1]:
				if first == -1:
					first = i
					change += 1
				elif last == -1:
					last = i + 1
					change += 1
				if change == 2:
					if s[first] != s[last]:
						flag = 1
						if last - first + 1 <= maximum:
							maximum = last - first + 1
						i = last - 1
						first = -1
						last = -1
						change = 0
					else:
						i = last - 1
						first = -1
						last = -1
						change = 0
				else:
					i += 1
			else:
				i += 1
		if flag == 0:
			print(0)
		else:
			print(maximum)
	else:
		print(0)


t = int(input())
for i in range(t):
	s = input()
	a1 = -1
	b1 = -1
	c1 = -1
	ans = 999999999
	for j in range(len(s)):
		if s[j] == '1':
			if a1 == -1:
				a1 = j
			else:
				a1 = j
				if b1 != -1 and c1 != -1:
					ans = min(ans, max(abs(b1 - a1), abs(c1 - a1), abs(c1 - b1)))
		if s[j] == '2':
			if b1 == -1:
				b1 = j
			else:
				b1 = j
				if a1 != -1 and c1 != -1:
					ans = min(ans, max(abs(b1 - a1), abs(c1 - a1), abs(c1 - b1)))
		if s[j] == '3':
			if c1 == -1:
				c1 = j
			else:
				c1 = j
		if b1 != -1 and a1 != -1 and (c1 != -1):
			ans = min(ans, max(abs(b1 - a1), abs(c1 - a1), abs(c1 - b1)))
	if ans != 999999999:
		print(ans + 1)
	else:
		print(0)


import os
import sys
from io import BytesIO, IOBase

def iin():
	return int(input())

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

def main():
	T = iin()
	for _ in range(T):
		s = input()
		a = [-1, -1, -1]
		ans = len(s)
		pos = 0
		for i in s:
			pos += 1
			if i == '1':
				a[0] = pos
			elif i == '2':
				a[1] = pos
			else:
				a[2] = pos
			if min(a) > 0:
				ans = min(ans, max(a) - min(a) + 1)
		if min(a) == -1:
			print(0)
		else:
			print(ans)
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))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


import re
t = int(input())
while t > 0:
	s = input()
	arr = re.findall('1[2]+3', s) + re.findall('1[3]+2', s) + re.findall('2[1]+3', s) + re.findall('2[3]+1', s) + re.findall('3[1]+2', s) + re.findall('3[2]+1', s)
	if arr != []:
		min_len = len(arr[0])
		for a in arr[1:]:
			min_len = min(min_len, len(a))
		print(min_len)
	else:
		print(0)
	t -= 1


from sys import stdin
input = stdin.readline
INF = 10 ** 9 + 7
MAX = 10 ** 7 + 7
MOD = 10 ** 9 + 7
for Ti in range(int(input().strip())):
	s = input().strip()
	ind = {str(x): float('-inf') for x in [1, 2, 3]}
	ans = float('inf')
	for (i, si) in enumerate(s):
		ind[si] = i
		ans = min(ans, max(ind.values()) - min(ind.values()) + 1)
	print(ans if ans != float('inf') else 0)


t = int(input())
for k in range(0, t):
	s = input()
	l = len(s)
	a = ''
	a += s[0]
	b = []
	b += [1]
	j = 0
	m = 2 * l
	for i in range(1, l):
		if s[i] != s[i - 1]:
			j += 1
			a += s[i]
			b += [1]
			if j >= 2 and a[j] != a[j - 2]:
				m = min(m, b[j - 1] + 2)
		else:
			b[j] += 1
	if m == 2 * l:
		print(0)
	else:
		print(m)


for _ in range(int(input())):
	s = input()
	size = float('inf')
	trip = [-1, -1, -1]
	for i in range(len(s)):
		trip[int(s[i]) - 1] = i
		if -1 not in trip:
			val = max(trip) - min(trip) + 1
			if size > val:
				size = val
	if size == float('inf'):
		print(0)
	else:
		print(size)


import math
t = int(input())
for _ in range(t):
	s = input()
	d = set()
	for i in s:
		if i not in d:
			d.add(i)
	if len(d) != 3:
		print(0)
	else:
		q = []
		f = 0
		for i in range(len(s)):
			if s[i] == '1':
				if f == 0:
					l1 = i
					f = 1
			elif f == 1:
				r1 = i
				f = 0
				if l1 != 0 and s[l1 - 1] != s[r1]:
					q.append(r1 - l1)
		f = 0
		for i in range(len(s)):
			if s[i] == '2':
				if f == 0:
					l2 = i
					f = 1
				f = 1
			elif f == 1:
				r2 = i
				f = 0
				if l2 != 0 and s[l2 - 1] != s[r2]:
					q.append(r2 - l2)
		f = 0
		for i in range(len(s)):
			if s[i] == '3':
				if f == 0:
					l3 = i
					f = 1
			elif f == 1:
				r3 = i
				f = 0
				if l3 != 0 and s[l3 - 1] != s[r3]:
					q.append(r3 - l3)
		print(min(q) + 2)


t = int(input())
i = 0
while i < t:
	n = input()
	s = [False] * 3
	a = -1
	b = -1
	c = -1
	res = float('inf')
	for x in range(len(n)):
		d = int(n[x]) - 1
		s[d] = True
		if d == 0:
			a = x
		if d == 1:
			b = x
		if d == 2:
			c = x
		if s.count(True) == 3:
			diff = max(a, b, c) - min(a, b, c) + 1
			res = min(res, diff)
	if res == float('inf'):
		print(0)
	else:
		print(res)
	i = i + 1


import sys

def solve():
	string = sys.stdin.readline().strip()
	length = len(string)
	answer = float('inf')
	flags = {'1': 0, '2': 0, '3': 0}
	if len(set(string)) == 3:
		(l, r) = (0, 1)
		flags[string[l]] += 1
		while r <= length:
			if all(flags.values()):
				answer = min(answer, r - l)
				flags[string[l]] -= 1
				l += 1
			else:
				if r < length:
					flags[string[r]] += 1
				r += 1
	if answer == float('inf'):
		answer = 0
	print(answer)

def main():
	n = int(sys.stdin.readline().strip())
	while n:
		solve()
		n -= 1
main()


t = int(input())
for _ in range(t):
	a = input()
	min_len = 10 ** 9
	l = 0
	fre = [0] * 4
	diff = 0
	for r in range(len(a)):
		c = ord(a[r]) - ord('0')
		if fre[c] == 0:
			diff += 1
		fre[c] += 1
		while diff == 3:
			min_len = min(min_len, r - l + 1)
			c = ord(a[l]) - ord('0')
			if fre[c] == 1:
				diff -= 1
			fre[c] -= 1
			l += 1
	print(min_len if min_len != 10 ** 9 else 0)


from collections import defaultdict
n = int(input())

def get_result(string):
	window_start = 0
	chars = set()
	min_len = None
	memory = defaultdict(int)
	for window_end in range(len(string)):
		chars.add(string[window_end])
		memory[string[window_end]] += 1
		if len(chars) == 3:
			while any([True for val in memory.values() if val > 1]):
				if memory[string[window_start]] - 1 == 0:
					break
				memory[string[window_start]] -= 1
				window_start += 1
			window_size = window_end - window_start + 1
			if min_len is None or window_size < min_len:
				min_len = window_size
	return min_len or 0
for i in range(n):
	string = input()
	print(get_result(string))


list_ans = []
for _ in range(int(input())):
	s = input()
	dict1 = {1: 200000, 2: 200000, 3: 200000}
	a = 1
	if '1' in s and '2' in s and ('3' in s):
		for i in range(len(s) - 1):
			if s[i] != s[i + 1]:
				break
		for x in range(i + 1, len(s) - 1):
			if s[x] == s[x + 1]:
				a += 1
			else:
				if s[x + 1] != s[x - a]:
					dict1[int(s[x])] = min(dict1[int(s[x])], a)
				a = 1
		list_ans.append(min(dict1.values()) + 2)
	else:
		list_ans.append(0)
for item in list_ans:
	print(item)


def solve():
	s = input()
	n = len(s)
	i1 = -1
	i2 = -1
	i3 = -1
	res = n + 1
	for i in range(n):
		if s[i] == '1':
			i1 = i
		if s[i] == '2':
			i2 = i
		if s[i] == '3':
			i3 = i
		if i1 != -1 and i2 != -1 and (i3 != -1):
			x = max(i1, i2, i3) - min(i1, i2, i3) + 1
			if x < res:
				res = x
	if res > n:
		return 0
	return res

def main():
	t = int(input())
	while t:
		print(solve())
		t -= 1
main()


for _ in range(int(input())):
	s = input()
	l = [-len(s) - 1] * 3
	res = len(s)
	for i in range(len(s)):
		c = ord(s[i]) - ord('1')
		l[c] = i
		length = i - min(l) + 1
		res = min(res, length)
	if min(l) < 0:
		res = 0
	print(res)


t = int(input())
for i in range(t):
	s = input()
	checker = [-1 for j in range(3)]
	ans = float('inf')
	for j in range(len(s)):
		if s[j] == '1':
			checker[0] = j
		elif s[j] == '2':
			checker[1] = j
		elif s[j] == '3':
			checker[2] = j
		if -1 not in checker:
			ans = min(ans, max(checker) - min(checker) + 1)
	if -1 in checker:
		ans = 0
	print(ans)


def check(l1, mini):
	if l1[0] >= 0 and l1[1] >= 0 and (l1[2] >= 0):
		ele = max(l1) - min(l1) + 1
		if mini > ele:
			return ele
	return mini
for _ in range(int(input())):
	s = input().strip()
	mini = 9999999999999
	l = [-1, -1, -1]
	for i in range(len(s)):
		if int(s[i]) == 1:
			l[0] = i
			mini = check(l, mini)
		elif int(s[i]) == 2:
			l[1] = i
			mini = check(l, mini)
		elif int(s[i]) == 3:
			l[2] = i
			mini = check(l, mini)
		if mini == 3:
			break
	print(0 if mini == 9999999999999 else mini)


import math, sys
t = int(input())
for _ in range(t):
	s = input()
	a = []
	cnt = 0
	for i in range(len(s)):
		cnt += 1
		if i != len(s) - 1:
			if s[i + 1] != s[i]:
				a.append((int(s[i]), cnt))
				cnt = 0
		else:
			a.append((int(s[i]), cnt))
	result = 1000000000000
	for i in range(len(a) - 2):
		e = a[i][0] * a[i + 1][0]
		e = e * a[i + 2][0]
		if e == 6:
			result = min(result, 2 + a[i + 1][1])
	if result > len(s) + 100:
		result = 0
	print(result)


n = int(input())
for _ in range(n):
	s = input()
	i = j = 0
	ib = 0
	jb = 10 ** 6
	kol = [0, 0, 0]
	k = len(s)
	while i < k:
		if j < k and (kol[0] == 0 or kol[1] == 0 or kol[2] == 0):
			kol[int(s[j]) - 1] += 1
			j += 1
		else:
			if j - i < jb - ib and kol[0] != 0 and (kol[1] != 0) and (kol[2] != 0):
				ib = i
				jb = j
			kol[int(s[i]) - 1] -= 1
			i += 1
	if kol[0] != 0 and kol[1] != 0 and (kol[2] != 0):
		if j - i < jb - ib:
			ib = i
			jb = j
	if jb - ib == 10 ** 6:
		jb = 0
	print(jb - ib)


import sys
no_of_chars = 256

def fun(string, pat):
	len1 = len(string)
	len2 = len(pat)
	if len1 < len2:
		return 0
	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 0
	return min_len
t = sys.stdin.readline()
ans = []
for _ in range(int(t)):
	s = list(input())
	ans.append(fun(s, '123'))
for i in ans:
	print(i)


t = int(input())
for _ in range(t):
	st = input()
	s = {}
	mini = 1000000000
	c = 0
	for i in st:
		s[i] = c
		if len(s.keys()) == 3:
			mini = min(mini, int(max(s.values())) - int(min(s.values())) + 1)
		c = c + 1
	if mini == 1000000000:
		print(0)
		continue
	print(mini)


from sys import stdin
input = stdin.readline
q = int(input())
for _ in range(q):
	s = input()
	n = len(s)
	close1left = [9327589327985] * n
	close1right = [3579823759823789] * n
	close2left = [325723983534] * n
	close2right = [5324857234853] * n
	ind = 0
	for i in range(n):
		if s[i] == '3':
			if ind <= i:
				ind = i + 1
			while ind < n:
				if s[ind] == '1':
					close1right[i] = ind - i
					break
				else:
					ind += 1
	ind = 0
	for i in range(n):
		if s[i] == '3':
			if ind <= i:
				ind = i + 1
			while ind < n:
				if s[ind] == '2':
					close2right[i] = ind - i
					break
				else:
					ind += 1
	ind = n - 1
	for j in range(n):
		i = n - 1 - j
		if s[i] == '3':
			if ind >= i:
				ind = i - 1
			while ind >= 0:
				if s[ind] == '1':
					close1left[i] = i - ind
					break
				ind -= 1
	ind = n - 1
	for j in range(n):
		i = n - 1 - j
		if s[i] == '3':
			if ind >= i:
				ind = i - 1
			while ind >= 0:
				if s[ind] == '2':
					close2left[i] = i - ind
					break
				else:
					ind -= 1
	res = 932489723984238
	for i in range(n):
		a = 1 + max(close2left[i], close1left[i])
		b = 1 + close2left[i] + close1right[i]
		c = 1 + close2right[i] + close1left[i]
		d = 1 + max(close2right[i], close1right[i])
		res = min(res, min(a, b, c, d))
	if res < 66666666:
		print(res)
	else:
		print(0)


t = int(input())
for i in range(t):
	s = list(input())
	l = []
	current = int(s[0])
	cnt = 1
	for j in range(1, len(s)):
		if int(s[j]) != current:
			l.append([current, cnt])
			cnt = 0
		current = int(s[j])
		cnt += 1
	l.append([current, cnt])
	a = [j[0] for j in l]
	li = []
	for j in range(len(a) - 2):
		if len(set(a[j:j + 3])) == 3:
			li.append(2 + l[j + 1][1])
	try:
		print(min(li))
	except:
		print(0)


n = int(input())
for i in range(n):
	s = input()
	l = []
	count = 0
	ans = float('inf')
	count1 = 0
	count2 = 0
	t = -1
	for l1 in s:
		if l1 == '1':
			count += 1
		elif l1 == '2':
			count1 += 1
		else:
			count2 += 1
	if count > 0 and count1 > 0 and (count2 > 0):
		for j in s:
			if t == -1 or j != l[t][0]:
				l.append([j, 1])
				t += 1
			else:
				l[t][1] += 1
		for k in range(1, t):
			if l[k - 1][0] != l[k + 1][0]:
				ans = min(ans, l[k][1] + 2)
		print(ans)
	else:
		print(0)


t = int(input())
for _ in range(t):
	s = input()
	ones = -1
	twos = -1
	threes = -1
	ans = 1e+20
	for ind in range(len(s)):
		if s[ind] == '1':
			ones = ind
		elif s[ind] == '2':
			twos = ind
		else:
			threes = ind
		if min(ones, twos, threes) != -1 and ind - min(ones, twos, threes) < ans:
			ans = max(ones, twos, threes) - min(ones, twos, threes)
	if ans != 1e+20:
		print(ans + 1)
	else:
		print(0)


n = int(input())
for _ in range(n):
	string = input()
	(n1, n2, n3) = (string[0], 0, 0)
	(pos1, pos2, pos3) = (0, -1, -1)
	rs = []
	for i in range(1, len(string)):
		if n2 == 0:
			if string[i] == n1:
				pos1 = i
			else:
				pos2 = i
				n2 = string[i]
		elif string[i] == n1:
			temp = i
			pos1 = pos2
			pos2 = i
			temp = n2
			n2 = n1
			n1 = temp
		elif string[i] == n2:
			pos2 = i
		else:
			pos3 = i
			rs_temp = pos3 - pos1 + 1
			if rs_temp == 3:
				rs.append(rs_temp)
				break
			else:
				rs.append(rs_temp)
				pos1 = pos2
				pos2 = pos3
				temp = n2
				n1 = n2
				n2 = string[i]
	if pos3 == -1:
		print(0)
	else:
		pass
		print(min(rs))


for _ in range(int(input())):
	s = str(input())
	list = []
	sets = set()
	have = False
	mins = 1000000000
	for x in s:
		if len(list) == 0:
			list.append(x)
			sets.add(x)
		elif x == list[0]:
			xx = list[-1]
			list = []
			list.append(xx)
			list.append(x)
			if xx == x:
				list.pop()
			sets.clear()
			sets.add(x)
			sets.add(xx)
		else:
			sets.add(x)
			list.append(x)
		if len(sets) == 3:
			if mins > len(list):
				mins = len(list)
			have = True
			xx = list[-1]
			xxx = list[-2]
			list = []
			list.append(xxx)
			list.append(xx)
			sets.clear()
			sets.add(xx)
			sets.add(xxx)
	if have:
		print(mins)
	else:
		print(0)


t = int(input())
for i in range(t):
	s = input()
	one = s.count('1')
	two = s.count('2')
	three = s.count('3')
	if one < 1 or two < 1 or three < 1:
		print(0)
	else:
		slen = len(s)
		res = slen
		one = 0
		two = 0
		three = 0
		right = 0
		for left in range(slen):
			while right < slen:
				if one < 1 or two < 1 or three < 1:
					if s[right] == '1':
						one += 1
					elif s[right] == '2':
						two += 1
					else:
						three += 1
					right += 1
				else:
					break
			if one >= 1 and two >= 1 and (three >= 1):
				res = min(res, one + two + three)
			else:
				pass
			if right == left:
				right += 1
			elif s[left] == '1':
				one -= 1
			elif s[left] == '2':
				two -= 1
			else:
				three -= 1
		print(res)


import os
import sys
from io import BytesIO, IOBase
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))
input = lambda : sys.stdin.readline().rstrip('\r\n')
no_of_chars = 256

def findSubString(string, pat):
	len1 = len(string)
	len2 = len(pat)
	if len1 < len2:
		print('No such window exists')
		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:
		print('No such window exists')
		return ''
	return string[start_index:start_index + min_len]
for rt in range(int(input())):
	s = input()
	if len(set(s)) < 3:
		print(0)
		continue
	else:
		print(len(findSubString(s, '123')))


for _ in range(int(input())):
	s = list(input())
	n = len(s)
	if '1' in s and '2' in s and ('3' in s):
		a = [0] * n
		b = [0] * n
		c = [0] * n
		if s[0] == '1':
			a[0] = 1
		elif s[0] == '2':
			b[0] = 1
		else:
			c[0] = 1
		j = 0
		ans = n
		for i in range(1, n):
			a[i] = a[i - 1]
			b[i] = b[i - 1]
			c[i] = c[i - 1]
			if s[i] == '1':
				a[i] += 1
			elif s[i] == '2':
				b[i] += 1
			else:
				c[i] += 1
			if a[i] > 0 and b[i] > 0 and (c[i] > 0):
				lenn = i - j + 1
				ans = min(ans, lenn)
				while j < i:
					if s[j] == '1':
						a[i] -= 1
					elif s[j] == '2':
						b[i] -= 1
					else:
						c[i] -= 1
					if a[i] > 0 and b[i] > 0 and (c[i] > 0):
						lenn -= 1
						ans = min(ans, lenn)
						j += 1
					else:
						j += 1
						break
				ans = min(ans, lenn)
		print(ans)
	else:
		print(0)


for _ in range(int(input())):
	s = input()
	n = len(s)
	ind = [n, n, n]
	ans = 3456789234
	(one, two, three) = (s.count('1'), s.count('2'), s.count('3'))
	if one == 0 or two == 0 or three == 0:
		print(0)
	else:
		for i in range(0, n):
			if s[i] == '1':
				ind[0] = i
			elif s[i] == '2':
				ind[1] = i
			elif s[i] == '3':
				ind[2] = i
			l = ind[:]
			l.sort()
			ans = min(ans, l[2] - l[0] + 1)
		print(ans)


tc = int(input())
while tc > 0:
	p1 = float('-inf')
	p2 = float('-inf')
	p3 = float('-inf')
	pos = 1
	best = float('inf')
	for c in input():
		if c == '1':
			p1 = pos
		elif c == '2':
			p2 = pos
		else:
			p3 = pos
		best = min(best, pos - min(p1, p2, p3) + 1)
		pos += 1
	print(0 if best > pos else best)
	tc -= 1


import sys
from os import path
if path.exists('C:/Users/prana/Desktop/sublime/input.txt'):
	sys.stdin = open('C:/Users/prana/Desktop/sublime/input.txt', 'r')
	sys.stdout = open('C:/Users/prana/Desktop/sublime/output.txt', 'w')
no_of_chars = 256

def f(string, pat):
	len1 = len(string)
	len2 = len(pat)
	if len1 < len2:
		print('No such window exists')
		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:
		print('No such window exists')
		return ''
	return string[start_index:start_index + min_len]

def solve():
	d = {'1': 0, '2': 0, '3': 0}
	s = input()
	s = list(s)
	for i in s:
		d[i] += 1
	if d['1'] == 0 or d['2'] == 0 or d['3'] == 0:
		print(0)
	else:
		ans = f(s, '123')
		print(len(ans))
T = 1
T = int(input())
for _ in range(1, T + 1):
	print('Case #', _, file=sys.stderr)
	solve()


from collections import *

def check(k):
	global s
	d = defaultdict(lambda : 0)
	for i in range(k - 1):
		d[s[i]] += 1
	for j in range(k - 1, len(s)):
		d[s[j]] += 1
		if d['3'] > 0 and d['1'] > 0 and (d['2'] > 0):
			return 1
		d[s[j - k + 1]] -= 1
	return 0
for _ in range(int(input())):
	s = input()
	low = 3
	res = 10 ** 9
	high = len(s)
	while low <= high:
		mid = (low + high) // 2
		if check(mid):
			high = mid - 1
			res = min(res, mid)
		else:
			low = mid + 1
	if res == 10 ** 9:
		print(0)
	else:
		print(res)


for _ in range(int(input())):
	n = input()
	n = list(n)
	s = set()
	c = len(n)
	d = {'1': 0, '2': 0, '3': 0}
	for i in range(len(n)):
		if n[i] in s:
			d[n[i]] = i
		else:
			s.add(n[i])
			d[n[i]] = i
		if len(s) == 3:
			u = max(list(d.values())) - min(list(d.values()))
			c = min(c, u)
			s.remove(n[min(list(d.values()))])
	if c == len(n):
		print(0)
	else:
		print(c + 1)


for _ in range(int(input())):
	seen = {'1': -1, '2': -1, '3': -1}
	s = input()
	best = len(s) + 1
	vals = seen.values()
	for i in range(len(s)):
		seen[s[i]] = i
		if -1 not in vals:
			best = min(best, max(vals) - min(vals) + 1)
	if best == len(s) + 1:
		print(0)
	else:
		print(best)


t = int(input())
for _ in range(t):
	s = input()
	arr = [-1] * 3
	res = float('inf')
	for i in range(len(s)):
		if -1 not in arr:
			val = max(arr) - min(arr) + 1
			res = min(res, val)
		if s[i] == '1':
			arr[0] = i
		elif s[i] == '2':
			arr[1] = i
		else:
			arr[2] = i
	if -1 not in arr:
		val = max(arr) - min(arr) + 1
		res = min(res, val)
		print(res)
	else:
		print(0)


import os
import operator
import sys
from collections import defaultdict
from io import BytesIO, IOBase

def main():
	for _ in range(int(input())):
		st = input()
		if len(st) == 1:
			print(0)
			continue
		if len(st) == 2:
			print(0)
			continue
		dic = defaultdict(list)
		ca = 0
		cb = 0
		cc = 0
		i = 0
		j = 0
		lis = []
		res = 10 ** 9
		while j < len(st):
			if st[j] == '1':
				ca += 1
			if st[j] == '2':
				cb += 1
			if st[j] == '3':
				cc += 1
			if ca > 0 and cb > 0 and (cc > 0):
				res = min(res, ca + cb + cc)
				while ca > 0 and cb > 0 and (cc > 0):
					if st[i] == '1':
						ca -= 1
					if st[i] == '2':
						cb -= 1
					if st[i] == '3':
						cc -= 1
					if ca > 0 and cb > 0 and (cc > 0):
						res = min(res, ca + cb + cc)
						i += 1
					else:
						i += 1
						break
			j += 1
		if res < 10 ** 9:
			print(res)
		else:
			print(0)
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))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


for _ in range(int(input())):
	s = input()
	List = []
	i = 0
	while i < len(s):
		count = 1
		j = i + 1
		while j < len(s) and s[i] == s[j]:
			count += 1
			j += 1
		List.append((int(s[i]), count))
		i = j
	ans = float('inf')
	for i in range(1, len(List) - 1):
		if List[i - 1][0] + List[i + 1][0] + List[i][0] == 6:
			ans = min(ans, List[i][1] + 2)
	print(0) if ans == float('inf') else print(ans)


import math
for _ in range(int(input())):
	s = input()
	(l1, l2, l3) = (-1, -1, -1)
	minn = 10 ** 6
	for (i, j) in enumerate(s):
		if j == '1':
			l1 = i
		elif j == '2':
			l2 = i
		elif j == '3':
			l3 = i
		if l1 != -1 and l2 != -1 and (l3 != -1):
			ans = max(l1, l2, l3) - min(l1, l2, l3) + 1
			if ans < minn:
				minn = ans
	if minn == 10 ** 6:
		print(0)
	else:
		print(minn)


def solve():
	s = input()
	run_lengths = []
	for x in s:
		if len(run_lengths) == 0 or x != run_lengths[-1][0]:
			run_lengths.append([x, 1])
		else:
			run_lengths[-1][1] += 1
	ans = len(s) + 1
	for i in range(1, len(run_lengths) - 1):
		if run_lengths[i - 1][0] != run_lengths[i + 1][0]:
			ans = min(ans, run_lengths[i][1] + 2)
	if ans > len(s):
		ans = 0
	print(ans)
t = int(input())
for _ in range(t):
	solve()


import sys
import math
from collections import defaultdict

def solve(test):
	s = list(input())
	n = len(s)
	rec = set(s)
	char = {'1': 0, '2': 0, '3': 0}
	if not ('1' in rec and '2' in rec and ('3' in rec)):
		print(0)
		return
	(start, end) = (0, 0)
	ans = sys.maxsize
	while end <= n:
		flag = 1
		for c in char:
			if char[c] < 1:
				flag = 0
				break
		if flag:
			ans = min(ans, end - start)
			char[s[start]] -= 1
			start += 1
		else:
			if end == n:
				break
			char[s[end]] += 1
			end += 1
			flag = 0
	print(ans)
test_cases = int(input())
for t in range(1, test_cases + 1):
	solve(t)


from collections import defaultdict

def smallest(s1, s2):
	assert s2 != ''
	d = defaultdict(int)
	nneg = [0]

	def incr(c):
		d[c] += 1
		if d[c] == 0:
			nneg[0] -= 1

	def decr(c):
		if d[c] == 0:
			nneg[0] += 1
		d[c] -= 1
	for c in s2:
		decr(c)
	minlen = len(s1) + 1
	j = 0
	for i in range(len(s1)):
		while nneg[0] > 0:
			if j >= len(s1):
				return minlen
			incr(s1[j])
			j += 1
		minlen = min(minlen, j - i)
		decr(s1[i])
	return minlen
for i in range(int(input())):
	s1 = str(input())
	a = '1'
	b = '2'
	c = '3'
	x = 0
	y = 0
	z = 0
	for i in range(len(s1)):
		if s1[i] == a:
			x += 1
		elif s1[i] == b:
			y += 1
		elif s1[i] == c:
			z += 1
	s2 = '123'
	if x < 1 or y < 1 or z < 1:
		ans = 0
	else:
		ans = smallest(s1, s2)
	print(ans)


for _ in range(int(input())):
	count = [0, 0, 0, 0]
	a = input()
	res = 200005
	if len(set(a)) == 3:
		left = 0
		right = 0
		while right < len(a) and res != 3:
			count[int(a[right])] += 1
			right += 1
			while count[1] and count[2] and count[3]:
				res = min(res, right - left)
				count[int(a[left])] -= 1
				left += 1
	if res == 200005:
		print(0)
	else:
		print(res)


t = int(input())
while t:
	t -= 1
	s = input()
	ans = 0
	if '1' not in s or '2' not in s or '3' not in s:
		print(ans)
		continue
	lst = []
	curr = 1
	tmp = s[0]
	for i in range(1, len(s)):
		if s[i] == tmp:
			curr += 1
		else:
			lst.append((tmp, curr))
			curr = 1
			tmp = s[i]
	lst.append((tmp, curr))
	ans = 10000000000009
	for i in range(len(lst) - 2):
		if lst[i][0] != lst[i + 1][0] and lst[i + 1][0] != lst[i + 2][0] and (lst[i][0] != lst[i + 2][0]):
			ans = min(ans, lst[i + 1][1] + 2)
	print(ans)


from math import *
t = int(input())
m = []
n = []
for i in range(t):
	m.append(input())
for i in range(t):
	n1 = -1
	n2 = -1
	n3 = -1
	flag = 0
	dist = 20000000
	for j in range(len(m[i])):
		if m[i][j] == '1':
			n1 = j
		elif m[i][j] == '2':
			n2 = j
		else:
			n3 = j
		if n1 > -1 and n2 > -1 and (n3 > -1):
			dist = min(dist, max(abs(n1 - n2) + 1, abs(n1 - n3) + 1, abs(n2 - n3) + 1))
	if dist == 20000000:
		dist = 0
	print(dist)


class StateMachine:

	def __init__(self):
		self.h = {'1': None, '2': None, '3': None, '12': None, '13': None, '23': None}

	def update(self, i, c):
		h = self.h
		if c == '1':
			h['1'] = i
			h['12'] = h['2']
			h['13'] = h['3']
			return h['23']
		if c == '2':
			h['2'] = i
			h['12'] = h['1']
			h['23'] = h['3']
			return h['13']
		if c == '3':
			h['3'] = i
			h['13'] = h['1']
			h['23'] = h['2']
			return h['12']

def minlength(s):
	sm = StateMachine()
	best = None
	bestbeg = None
	for (i, c) in enumerate(s):
		beg = sm.update(i, c)
		if beg is not None:
			length = i - beg + 1
			if best is None or length < best:
				best = length
				bestbeg = beg
	return 0 if best is None else best
t = int(input().strip())
for _ in range(t):
	s = input().strip()
	print(minlength(s))


def findSubString(string, pat):
	n1 = len(string)
	if n1 < 3:
		return 0
	hp = [0] * (n1 + 1)
	hs = [0] * (n1 + 1)
	for i in range(3):
		hp[int(pat[i])] += 1
	(s1, ind, mi) = (0, -1, float('inf'))
	c = 0
	for j in range(n1):
		hs[int(string[j])] += 1
		if hp[int(string[j])] != 0 and hs[int(string[j])] <= hp[int(string[j])]:
			c += 1
		if c == 3:
			while hs[int(string[s1])] > hp[int(string[s1])] or hp[int(string[s1])] == 0:
				if hs[int(string[s1])] > hp[int(string[s1])]:
					hs[int(string[s1])] -= 1
				s1 += 1
			lw = j - s1 + 1
			if mi > lw:
				mi = lw
				ind = s1
	if ind == -1:
		return 0
	return mi
t = int(input())
for w in range(t):
	s = input()
	print(findSubString(s, '123'))


for _ in range(int(input())):
	n = input()
	l = list(n)
	min = 2 ** 31
	t = [-1, -1, -1]
	for i in range(len(l)):
		if l[i] == '1':
			t[0] = i + 1
		elif l[i] == '2':
			t[1] = i + 1
		else:
			t[2] = i + 1
		t4 = sorted(t)
		if -1 not in t:
			t2 = t4[2] - t4[0]
			if min > t2:
				min = t2
	if -1 in t:
		print('0')
	else:
		print(min + 1)


def find_longest_sequence(number):
	best_length = float('inf')
	curr_solution = []
	used_digits = set()
	groups = find_groups(number)
	for group in groups:
		if group[0] not in used_digits:
			curr_solution.append(group)
			used_digits.add(group[0])
			if len(used_digits) == 3:
				best_length = min(best_length, 2 + curr_solution[1][1])
				used_digits.remove(curr_solution[0][0])
				curr_solution.pop(0)
		else:
			curr_solution.pop(0)
			curr_solution.append(group)
	return 0 if best_length == float('inf') else best_length

def find_groups(number):
	groups = []
	i = 0
	while i < len(number):
		element = number[i]
		count = 0
		while i < len(number) and number[i] == element:
			count += 1
			i += 1
		groups.append((element, count))
	return groups
numbers = []
for _ in range(int(input())):
	numbers.append(input())
for number in numbers:
	print(find_longest_sequence(number))


import math
import sys

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

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

def insr():
	s = input()
	return list(s[:len(s) - 1])

def invr():
	return map(int, input().split())
test_cases = int(input())
for _ in range(test_cases):
	sequence = str(input())
	ans = float('inf')
	i = 0
	while i < len(sequence) - 1:
		a = sequence[i]
		if sequence[i + 1] == a:
			i += 1
			continue
		else:
			b = sequence[i + 1]
			for j in range(i + 2, len(sequence)):
				if sequence[j] != a and sequence[j] != b:
					ans = min(ans, j - i + 1)
					i = j - 2
					break
				if sequence[j] == a:
					i = j - 2
					break
		i += 1
	if ans == float('inf'):
		print(0)
	else:
		print(ans)


def main():
	t = int(input())
	for _ in range(t):
		nums = list(input())
		if not ('1' in nums and '2' in nums and ('3' in nums)):
			print(0)
			continue
		last_idxx = [None, None, None]
		min_len = float('Inf')
		for (idx, num) in enumerate(nums):
			if num == '1':
				last_idxx[0] = idx
				min_len = check(idx, 1, 2, last_idxx, min_len)
			elif num == '2':
				last_idxx[1] = idx
				min_len = check(idx, 0, 2, last_idxx, min_len)
			else:
				last_idxx[2] = idx
				min_len = check(idx, 1, 0, last_idxx, min_len)
			if min_len == 3:
				break
		print(min_len)

def check(idx, idx1, idx2, last_idxx, min_len):
	if last_idxx[idx1] is not None and last_idxx[idx2] is not None:
		min_len = min(idx + 1 - min(last_idxx[idx1], last_idxx[idx2]), min_len)
	return min_len
main()


for tc in range(int(input())):
	s = input()
	idx = [-1, -1, -1]
	ans = 0
	for r in range(len(s)):
		idx[int(s[r]) - int('1')] = r
		l = sorted(idx)[0]
		if l == -1:
			continue
		ans = min(ans, r - l + 1) or r - l + 1
	print(ans)


from collections import defaultdict

def find_sub_string(str):
	str_len = len(str)
	dist_count_char = len(set(['1', '2', '3']))
	(ctr, start_pos, start_pos_index, min_len) = (0, 0, -1, 9999999999)
	curr_count = defaultdict(lambda : 0)
	for i in range(str_len):
		curr_count[str[i]] += 1
		if curr_count[str[i]] == 1:
			ctr += 1
		if ctr == dist_count_char:
			while curr_count[str[start_pos]] > 1:
				if curr_count[str[start_pos]] > 1:
					curr_count[str[start_pos]] -= 1
				start_pos += 1
			len_window = i - start_pos + 1
			if min_len > len_window:
				min_len = len_window
				start_pos_index = start_pos
	return len(str[start_pos_index:start_pos_index + min_len])
T = int(input())
for _ in range(T):
	S = input()
	res = find_sub_string(S)
	if res == 1:
		print(0)
	else:
		print(res)


for _ in range(int(input())):
	wah = list(map(int, input()))
	first = wah[0]
	second = -1
	third = -1
	min_size = 1000000000000
	size = 0
	last = 0
	for i in range(1, len(wah)):
		n = wah[i]
		last = i
		if n != first:
			second = n
			size = 2
			break
	for i in range(last + 1, len(wah)):
		n = wah[i]
		if n == first:
			size = 2
			(first, second) = (second, first)
		elif n == second:
			size += 1
		else:
			if size < min_size:
				min_size = size
			(first, second) = (second, n)
			size = 2
	if min_size == 1000000000000:
		print(0)
	else:
		print(min_size + 1)


from sys import stdin, stdout
import math
print = stdout.write
input = stdin.readline
for p in range(int(input())):
	st = input()
	a = -1
	b = -1
	c = -1
	ans = -1
	for i in range(len(st)):
		if st[i] == '1':
			a = i
		elif st[i] == '2':
			b = i
		elif st[i] == '3':
			c = i
		if a != -1 and b != -1 and (c != -1):
			d = max(a, b, c) - min(a, b, c) + 1
			if ans == -1:
				ans = d
			elif ans > d:
				ans = d
	if ans != -1:
		print(str(ans) + '\n')
	else:
		print('0\n')


import math
t = int(input())
for _ in range(t):
	n = list(input())
	a = {}
	ma = 9999999999
	l = [0] * 3
	if '1' not in n or '2' not in n or '3' not in n:
		print(0)
	else:
		for i in range(len(n)):
			a[n[i]] = i
			q = list(a.values())
			if len(q) == 3:
				z = max(q) - min(q) + 1
				if ma > z:
					ma = z
		print(ma)


def ternaryString(s):
	se = set(s)
	if '1' not in se or '2' not in se or '3' not in se:
		return 0
	cnt = dict()
	start = 0
	minWin = len(s)
	for end in range(len(s)):
		cnt[s[end]] = cnt.get(s[end], 0) + 1
		while cnt.get('1') and cnt.get('2') and cnt.get('3'):
			minWin = min(end - start + 1, minWin)
			cnt[s[start]] -= 1
			start += 1
	return minWin

def main():
	count = int(input())
	for i in range(count):
		case = input().strip()
		print(ternaryString(case))
main()


t = int(input())
for _ in range(t):
	s = str(input())
	s = list(s)
	s = list(map(int, s))
	s = [x - 1 for x in s]
	n = len(s)
	ans = 10 ** 18
	p = 0
	q = 0
	D = [0] * 3
	for p in range(n):
		while q < n and (D[0] == 0 or D[1] == 0 or D[2] == 0):
			D[s[q]] += 1
			q += 1
		if D[0] != 0 and D[1] != 0 and (D[2] != 0):
			ans = min(ans, q - p)
		if p == q:
			q += 1
		else:
			D[s[p]] -= 1
	if ans == 10 ** 18:
		print(0)
	else:
		print(ans)


def solve(s):
	if len(set(s)) != 3:
		print(0)
		return
	indexes = [s.index('1'), s.index('2'), s.index('3')]
	mini = max(indexes) - min(indexes) + 1
	for i in range(len(s)):
		indexes[int(s[i]) - 1] = i
		length = max(indexes) - min(indexes) + 1
		mini = min(mini, length)
	print(mini)
t = int(input())
for _ in range(t):
	s = list(input())
	solve(s)


from sys import stdin
input = stdin.readline
R = lambda : map(int, input().split())
for _ in range(int(input())):
	s = input().rstrip('\n')
	(a, b, c) = ([], [], [])
	if s.count('1') and s.count('2') and s.count('3'):
		ans = l = len(s)
		for i in range(l):
			if s[i] == '1':
				a += (i,)
			elif s[i] == '2':
				b += (i,)
			else:
				c += (i,)
			if a and b and c:
				ans1 = i - min(a[-1], b[-1], c[-1]) + 1
				if ans1 < ans:
					ans = ans1
		print(ans)
	else:
		print(0)


t = int(input())
for i in range(t):
	s = input()
	l = list(s)
	a = 0
	b = 0
	c = 0
	g = []
	if '1' in s and '2' in s and ('3' in s):
		if '123' in s or '132' in s or '213' in s or ('231' in s) or ('312' in s) or ('321' in s):
			print(3)
		else:
			for j in range(len(l)):
				if l[j] == '1':
					a = j + 1
				elif l[j] == '2':
					b = j + 1
				elif l[j] == '3':
					c = j + 1
				if a != 0 and b != 0 and (c != 0):
					g.append(max(a, b, c) - min(a, b, c) + 1)
					if min(a, b, c) == a:
						a = 0
					elif min(a, b, c) == b:
						b = 0
					elif min(a, b, c) == c:
						c = 0
			print(min(g))
	else:
		print(0)


t = int(input())
for _ in range(t):
	a = input()
	n = len(a)
	b = []
	i = -1
	j = -1
	k = -1
	for l in range(n):
		if a[l] == '1':
			i = l
		elif a[l] == '2':
			j = l
		elif a[l] == '3':
			k = l
		d = [i, j, k]
		if -1 not in d:
			b.append(max(d) - min(d) + 1)
	if len(b) == 0:
		print(0)
	else:
		print(min(b))


t = int(input())
ans = [0] * t
for i in range(t):
	S = [int(i) - 1 for i in input()]
	n = len(S)
	cnt = [0, 0, 0]
	r = 0
	c = 0
	add = 10 ** 9
	for l in range(n):
		if l != 0:
			cnt[S[l - 1]] -= 1
			if cnt[S[l - 1]] == 0:
				c -= 1
		while r < n and c != 3:
			if cnt[S[r]] == 0:
				c += 1
			cnt[S[r]] += 1
			r += 1
		if c != 3:
			break
		add = min(add, r - l)
	if add == 10 ** 9:
		ans[i] = 0
	else:
		ans[i] = add
for i in ans:
	print(i)


from collections import Counter
t = int(input())
strings = []
for i in range(t):
	strings.append(input())
for i in strings:
	min_len = len(i) + 1
	cntr = Counter({'1': 0, '2': 0, '3': 0})
	n = len(i)
	h = 0
	j = 0
	cntr[i[h]] += 1
	go = True
	while go:
		if cntr['1'] == 0 or cntr['2'] == 0 or cntr['3'] == 0:
			if j == n - 1:
				go = False
			else:
				j += 1
				cntr[i[j]] += 1
		else:
			if j - h + 1 < min_len:
				min_len = j - h + 1
			cntr[i[h]] -= 1
			h += 1
	if min_len == len(i) + 1:
		print(0)
	else:
		print(min_len)


for _ in range(int(input())):
	s = str(input())
	one = 0
	two = 0
	thr = 0
	onei = 0
	twoi = 0
	thri = 0
	f = 0
	ans = 10000000
	for i in range(len(s)):
		if s[i] == '1':
			onei = i
			one = 1
		elif s[i] == '2':
			twoi = i
			two = 1
		elif s[i] == '3':
			thri = i
			thr = 1
		if one == 1 and two == 1 and (thr == 1):
			f = 1
			ans = min(ans, max(onei, twoi, thri) - min(onei, twoi, thri) + 1)
	if f == 1:
		print(ans)
	else:
		print(0)


for _ in range(int(input())):
	s = input()
	st = set()
	n = len(s)
	d = {}
	l = []
	count = 1
	for i in range(1, n):
		if s[i] != s[i - 1]:
			l.append((s[i - 1], count))
			count = 1
		else:
			count += 1
	l.append((s[-1], count))
	ans = 10000000
	for i in range(len(l) - 2):
		st = set()
		st.add(l[i][0])
		st.add(l[i + 1][0])
		st.add(l[i + 2][0])
		if len(st) == 3:
			mn = 2 + l[i + 1][1]
			ans = min(ans, mn)
	if ans == 10000000:
		ans = 0
	print(ans)


t = int(input())
for _ in range(t):
	s = input()
	ans = 0
	l = [-1] * 3
	for i in range(len(s)):
		l[int(s[i]) - 1] = i
		if l[0] > -1 and l[1] > -1 and (l[2] > -1):
			if ans == 0:
				ans = max(l) - min(l) + 1
			else:
				ans = min(ans, max(l) - min(l) + 1)
	print(ans)


from sys import stdin, stdout
import math, sys
from itertools import permutations, combinations
from collections import defaultdict, deque, OrderedDict
from os import path
import bisect as bi
import heapq

def yes():
	print('YES')

def no():
	print('NO')
if path.exists('input.txt'):
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')

	def I():
		return int(input())

	def In():
		return map(int, input().split())
else:

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

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

def dict(a):
	d = {}
	for x in a:
		if d.get(x, -1) != -1:
			d[x] += 1
		else:
			d[x] = 1
	return d

def find_gt(a, x):
	i = bi.bisect_right(a, x)
	if i != len(a):
		return i
	else:
		return -1

def main():
	try:
		l = list(input())
		d = {'1': -1, '2': -1, '3': -1}
		count = 0
		ans = 10000000.0
		for x in range(len(l)):
			if d[l[x]] == -1:
				count += 1
				d[l[x]] = x
			else:
				d[l[x]] = x
			if count >= 3:
				ans = min(max(d.values()) - min(d.values()) + 1, ans)
		if count <= 2:
			print(0)
		else:
			print(ans)
	except:
		pass
M = 998244353
P = 1000000007
for _ in range(I()):
	main()


t = int(input())
for i in range(t):
	s = input()
	(count_type, count) = ([int(s[0])], [1])
	for i in range(1, len(s)):
		if s[i] == s[i - 1]:
			count[-1] += 1
		else:
			count_type.append(int(s[i]))
			count.append(1)
	min_len = len(s) + 1
	for i in range(1, len(count_type) - 1):
		if count_type[i - 1] != count_type[i] and count_type[i] != count_type[i + 1] and (count_type[i - 1] != count_type[i + 1]):
			if count[i] + 2 < min_len:
				min_len = count[i] + 2
	if min_len == len(s) + 1:
		print(0)
	else:
		print(min_len)


num = int(input())
for _ in range(num):
	ll = [-1, -1, -1]
	s = input()
	mi = 200000
	for i in range(len(s)):
		ll[ord(s[i]) - 49] = i
		if not -1 in ll:
			temp = max(ll) - min(ll)
			mi = mi if mi < temp else temp
	if mi == 200000:
		print('0')
	else:
		print(mi + 1)


T = int(input())
import math
n = [0] * T
m = [0] * T
a = [0] * T
p = [0] * T
for t in range(T):
	n[t] = list(input())
	out = 1000000.0
	ons = 0
	tws = 0
	thr = 0
	for i in n[t]:
		if i == '2':
			if ons:
				ons += 1
			if thr:
				thr += 1
			tws = 1
		elif i == '1':
			if tws:
				tws += 1
			if thr:
				thr += 1
			ons = 1
		else:
			if tws:
				tws += 1
			if ons:
				ons += 1
			thr = 1
		if ons and tws and thr:
			out = min(out, max((ons, tws, thr)))
	if out == 1000000.0:
		print(0)
	else:
		print(out)


for _ in range(int(input())):
	s = list(input())
	ans = 200001
	(x, y, z) = (-1, -1, -1)
	n = len(s)
	for i in range(n):
		if s[i] == '1':
			x = i
		elif s[i] == '2':
			y = i
		else:
			z = i
		if x != -1 and y != -1 and (z != -1):
			ans = min(ans, max(x, y, z) - min(x, y, z) + 1)
	print(ans if ans != 200001 else 0)


from collections import defaultdict

def smallest_sub_string(input_str):
	n = len(input_str)
	dist_count = len(set([x for x in input_str]))
	(count, start, start_index, min_len) = (0, 0, -1, 9999999999)
	curr_count = defaultdict(lambda : 0)
	for j in range(n):
		curr_count[input_str[j]] += 1
		if curr_count[input_str[j]] == 1:
			count += 1
		if count == dist_count:
			while curr_count[input_str[start]] > 1:
				if curr_count[input_str[start]] > 1:
					curr_count[input_str[start]] -= 1
				start += 1
			len_window = j - start + 1
			if min_len > len_window:
				min_len = len_window
				start_index = start
	return len(input_str[start_index:start_index + min_len])
for _ in range(int(input())):
	s = input()
	if '1' not in s or '2' not in s or '3' not in s:
		print(0)
	else:
		print(smallest_sub_string(s))


for _ in range(int(input())):
	s = input()
	vis = [-1] * 4
	l = len(s)
	p = l
	for i in range(p):
		vis[int(s[i])] = i
		if vis[1] != -1 and vis[2] != -1 and (vis[3] != -1):
			m = min(vis[1], vis[2], vis[3])
			n = max(vis[1], vis[2], vis[3])
			if n - m + 1 < l:
				l = n - m + 1
	if vis[1] != -1 and vis[2] != -1 and (vis[3] != -1):
		print(l)
	else:
		print(0)


Answers = []
for _ in range(int(input())):
	Check = [False] * 3
	Index = [0] * 3
	X = input()
	Size = len(X)
	Min = Size + 1
	index = 0
	while index < Size:
		if True not in Check:
			while index < Size - 1 and X[index] == X[index + 1]:
				index += 1
			Check[int(X[index]) - 1] = True
			Index[int(X[index]) - 1] = index
		else:
			Check[int(X[index]) - 1] = True
			Index[int(X[index]) - 1] = index
			if False not in Check:
				Min = min(Min, max(Index) - min(Index) + 1)
		index += 1
	Answers.append(str(Min) if Min != Size + 1 else str(0))
print('\n'.join(Answers))


import math, sys
from collections import defaultdict, Counter, deque
INF = float('inf')

def gcd(a, b):
	while b:
		(a, b) = (b, a % b)
	return a

def isPrime(n):
	if n <= 1:
		return False
	i = 2
	while i ** 2 <= n:
		if n % i == 0:
			return False
		i += 1
	return True

def primeFactors(n):
	factors = []
	i = 2
	while i ** 2 <= n:
		while n % i == 0:
			factors.append(i)
			n //= i
		i += 1
	if n > 1:
		factors.append(n)
	return factors

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

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

def c(n, r):
	return math.factorial(n) / (math.factorial(n - r) * math.factorial(r))

def main():
	s = input()
	n = len(s)
	i = 1
	ans = INF
	while i < n - 1:
		j = i
		while i + 1 < n - 1 and s[i + 1] == s[i]:
			i += 1
		if sorted([s[j - 1], s[i], s[i + 1]]) == ['1', '2', '3']:
			ans = min(ans, i + 1 - (j - 1) + 1)
		i += 1
	if ans == INF:
		print(0)
	else:
		print(ans)
t = int(input())
for _ in range(t):
	main()


import os
import sys
from io import BytesIO, IOBase
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')
t = int(input())
for _ in range(t):
	s = input()
	p1 = 0
	p2 = 0
	p3 = 0
	mi = 2000000
	(a, b, c) = (0, 0, 0)
	for i in range(len(s)):
		if s[i] == '1':
			p1 = i
			a = 1
		if s[i] == '2':
			p2 = i
			b = 1
		if s[i] == '3':
			p3 = i
			c = 1
		if a + b + c == 3:
			l = min(p1, p2, p3)
			r = max(p1, p2, p3)
			mi = min(mi, r - l)
	if mi == 2000000:
		print('0')
	else:
		print(mi + 1)


def find123(string):
	tuples = []
	repeat = 0
	for (i, char) in enumerate(string):
		repeat += 1
		if i == len(string) - 1 or char != string[i + 1]:
			tuples.append((char, repeat))
			repeat = 0
	viable = []
	for (i, pair) in enumerate(tuples):
		if i != 0 and i != len(tuples) - 1:
			left = tuples[i - 1]
			right = tuples[i + 1]
			if left[0] != right[0]:
				viable.append(pair[1])
	return min(viable) + 2 if len(viable) > 0 else 0
strings = []
num = int(input())
for j in range(num):
	strings.append(input().strip())
for string in strings:
	print(find123(string))


from __future__ import division, print_function
import sys
if sys.version_info[0] < 3:
	from __builtin__ import xrange as range
	from future_builtins import ascii, filter, hex, map, oct, zip
import os, sys, bisect, copy
from collections import defaultdict, Counter, deque
if os.path.exists('in.txt'):
	sys.stdin = open('in.txt', 'r')
if os.path.exists('out.txt'):
	sys.stdout = open('out.txt', 'w')

def input():
	return sys.stdin.readline()

def mapi(arg=0):
	return map(int if arg == 0 else str, input().split())
for _ in range(int(input())):
	a = input().strip()
	res = float('inf')
	n = len(a)
	mp = [[0] * 3 for i in range(n)]
	for i in range(3):
		mp[0][i] = -1
	mp[0][ord(a[0]) - ord('1')] = 0
	for i in range(1, n):
		for j in range(3):
			mp[i][j] = mp[i - 1][j]
		mp[i][ord(a[i]) - ord('1')] = i
	for i in range(2, n):
		tmp = min(mp[i])
		if tmp != -1:
			res = min(res, i - tmp + 1)
	print(res if res != float('inf') else 0)


for i in range(int(input())):
	a = input()
	(p, q, r) = (-1, -1, -1)
	n = len(a) + 1
	m = 0
	for j in range(n - 1):
		if a[j] == '1':
			p = j
		elif a[j] == '2':
			q = j
		else:
			r = j
		if p >= 0 and q >= 0 and (r >= 0):
			z = max([p, q, r]) - min([p, q, r]) + 1
			if z < n:
				n = z
				m = 1
		if n == 3:
			break
	if m == 0:
		print(0)
	else:
		print(n)


t = int(input())
no_of_chars = 256

def solve(string, pat):
	len1 = len(string)
	len2 = len(pat)
	if len1 < len2:
		return 0
	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 0
	return abs(start_index - start_index + min_len)
while t:
	t -= 1
	a = input()
	print(solve(a, '123'))


for _ in range(int(input())):
	s = input()
	if len(set(list(s))) < 3:
		print(0)
	else:
		data = []
		prev = s[0]
		count = 1
		for q in s[1:]:
			if q == prev:
				count += 1
			else:
				data.append([prev, count])
				prev = q
				count = 1
		data.append([prev, count])
		min = 10000000000
		for q in range(len(data) - 2):
			if len(set([data[q][0], data[q + 1][0], data[q + 2][0]])) == 3:
				temp = 1 + data[q + 1][1] + 1
				if temp < min:
					min = temp
		print(min)


def all(s):
	if '1' in s and '2' in s and ('3' in s):
		return True
	else:
		return False

def other(c):
	if c == '1':
		return ('2', '3')
	elif c == '2':
		return ('1', '3')
	elif c == '3':
		return ('1', '2')

def check(s):
	c = s[0]
	(n1, n2) = other(c)
	(l1, l2) = (pow(10, 10), pow(10, 10))
	try:
		l1 = s.index(n1)
	except:
		pass
	try:
		l2 = s.index(n2)
	except:
		pass
	if l1 < l2:
		return s[l1 - 1:]
	else:
		return s[l2 - 1:]
test = int(input())
for t in range(test):
	s_input = input()
	if not all(s_input):
		print('0')
		continue
	s_input = check(s_input)
	s_input = s_input[::-1]
	s_input = check(s_input)
	s_input = s_input[::-1]
	num = []
	rep = []
	count = 0
	for i in range(len(s_input)):
		if count == 0:
			count += 1
		elif s_input[i - 1] == s_input[i]:
			count += 1
		elif s_input[i - 1] != s_input[i]:
			num.append(s_input[i - 1])
			rep.append(count)
			count = 1
			if i == len(s_input) - 1:
				num.append(s_input[i])
				rep.append(count)
	m = []
	for i in range(len(num) - 2):
		if num[i] != num[i + 1] and num[i] != num[i + 2]:
			m.append(rep[i + 1] + 2)
	print(min(m))


def findSubString(string):
	len1 = len(string)
	len2 = 3
	if len1 < len2:
		return 0
	arr = [0] * 3
	(start, start_index, min_len) = (0, -1, float('inf'))
	count = 0
	for j in range(len1):
		arr[int(string[j]) - 1] += 1
		if arr[int(string[j]) - 1] <= 1:
			count += 1
		if count == len2:
			while arr[int(string[start]) - 1] > 1:
				if arr[int(string[start]) - 1] > 1:
					arr[int(string[start]) - 1] -= 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 0
	return min_len
for _ in range(int(input())):
	string = input()
	print(findSubString(string))


import math
T = int(input())
for test in range(1, T + 1):
	ans = -1
	s = input()
	if not ('1' in s and '2' in s and ('3' in s)):
		ans = 0
	else:
		string = []
		prev = s[0]
		cnt = 1
		for c in s[1:]:
			if c == prev:
				cnt += 1
			else:
				string.append([prev, cnt])
				cnt = 1
				prev = c
		string.append([prev, cnt])
		for (i, seg) in enumerate(string[1:-1]):
			prev = string[i]
			next = string[i + 2]
			if sorted([prev[0], seg[0], next[0]]) == ['1', '2', '3']:
				if ans == -1 or seg[1] + 2 < ans:
					ans = seg[1] + 2
	print('{:}'.format(ans))


for _ in range(int(input())):
	l = list(map(int, input()))
	if len(set(l)) != 3:
		print(0)
	else:
		dp = []
		last_3 = 100000000000000
		last_2 = 100000000000000
		last_1 = 100000000000000
		for i in range(1, len(l) + 1):
			if l[-i] == 3:
				last_3 = i
			elif l[-i] == 2:
				last_2 = i
			else:
				last_1 = i
			dp.append(max(last_1, last_2, last_3) - min(last_3, last_2, last_1) + 1)
		print(min(dp))


import sys
t = int(input())
while t > 0:
	s = input()
	pos1 = -1
	pos2 = -1
	pos3 = -1
	l = sys.maxsize
	for i in range(len(s)):
		if s[i] == '1':
			pos1 = i
		elif s[i] == '2':
			pos2 = i
		else:
			pos3 = i
		if pos1 != -1 and pos2 != -1 and (pos3 != -1):
			head = min(pos1, pos2, pos3)
			tail = max(pos1, pos2, pos3)
			l = min(l, tail - head + 1)
	if l != sys.maxsize:
		print(l)
	else:
		print(0)
	t -= 1


for i in range(int(input())):
	string = input()
	(f1, f2, f3) = (False, False, False)
	(i1, i2, i3) = (0, 0, 0)
	if '1' in string:
		if '2' in string:
			if '3' in string:
				length = len(string)
				ans = length
				for j in range(length):
					if string[j] == '1':
						f1 = True
						i1 = j
					elif string[j] == '2':
						f2 = True
						i2 = j
					elif string[j] == '3':
						f3 = True
						i3 = j
					if f1 and f2 and f3:
						li = [i1, i2, i3]
						val = max(li) - min(li) + 1
						if ans > val:
							ans = val
				print(ans)
			else:
				print(0)
		else:
			print(0)
	else:
		print(0)


from __future__ import division, print_function
import os, sys
from io import BytesIO, IOBase
if sys.version_info[0] < 3:
	from __builtin__ import xrange as range
	from future_builtins import ascii, filter, hex, map, oct, zip

def ii():
	return int(input())

def si():
	return input()

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

def li():
	return list(mi())

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

def gcd(x, y):
	while y:
		(x, y) = (y, x % y)
	return x
mod = 1000000007
import math
import bisect
abc = 'abcdefghijklmnopqrstuvwxyz'

def main():
	for _ in range(ii()):
		s = si()
		x = y = z = -1
		ans = 100000000.0
		for i in range(len(s)):
			if s[i] == '1':
				x = i
			elif s[i] == '2':
				y = i
			else:
				z = i
			if x >= 0 and y >= 0 and (z >= 0):
				c = min(x, y, z)
				d = max(x, y, z)
				ans = min(ans, d - c + 1)
		if ans == 100000000.0:
			ans = 0
		print(ans)
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):
	(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')
main()


import sys
import math
from collections import deque
for _ in range(int(input())):
	s = list(map(int, list(input())))
	minLength = len(s) + 1
	p1 = 0
	p2 = 0
	ar = [0] * 3
	for p2 in range(len(s)):
		ar[s[p2] - 1] += 1
		while ar[s[p1] - 1] > 1:
			ar[s[p1] - 1] -= 1
			p1 += 1
		if ar[0] > 0 and ar[1] > 0 and (ar[2] > 0):
			minLength = min(minLength, p2 - p1 + 1)
	if minLength == len(s) + 1:
		print(0)
	else:
		print(minLength)


t = int(input())
for _ in range(t):
	s = input()
	if len(set(s)) < 3:
		print(0)
	else:
		l = []
		n = len(s)
		c = 0
		f = int(s[0])
		for i in range(n):
			if s[i] == '1':
				if f == 1:
					c = c + 1
				else:
					l.append([f, c])
					c = 1
					f = 1
			elif s[i] == '2':
				if f == 2:
					c = c + 1
				else:
					l.append([f, c])
					f = 2
					c = 1
			elif s[i] == '3':
				if f == 3:
					c = c + 1
				else:
					l.append([f, c])
					f = 3
					c = 1
		l.append([f, c])
		i = 0
		x = 78678979890
		while i < len(l) - 2:
			if l[i][0] == 1:
				if l[i + 1][0] == 2:
					if l[i + 2][0] == 3:
						x = min(x, 1 + l[i + 1][1] + 1)
						i = i + 1
					else:
						i = i + 1
				elif l[i + 1][0] == 3:
					if l[i + 2][0] == 2:
						x = min(x, 1 + l[i + 1][1] + 1)
						i = i + 1
					else:
						i = i + 1
			elif l[i][0] == 2:
				if l[i + 1][0] == 1:
					if l[i + 2][0] == 3:
						x = min(x, 1 + l[i + 1][1] + 1)
						i = i + 1
					else:
						i = i + 1
				elif l[i + 1][0] == 3:
					if l[i + 2][0] == 1:
						x = min(x, 1 + l[i + 1][1] + 1)
						i = i + 1
					else:
						i = i + 1
			elif l[i][0] == 3:
				if l[i + 1][0] == 2:
					if l[i + 2][0] == 1:
						x = min(x, 1 + l[i + 1][1] + 1)
						i = i + 1
					else:
						i = i + 1
				elif l[i + 1][0] == 1:
					if l[i + 2][0] == 2:
						x = min(x, 1 + l[i + 1][1] + 1)
						i = i + 1
					else:
						i = i + 1
		print(x)


for _ in range(int(input())):
	s = input()
	b = 0
	e = 0
	c = [0, 0, 0]
	x = ['1', '2', '3']
	ans = int(1000000.0)
	while e != len(s):
		if s[e] == '1':
			c[0] += 1
			e += 1
		elif s[e] == '2':
			c[1] += 1
			e += 1
		else:
			c[2] += 1
			e += 1
		while c[0] > 0 and c[1] > 0 and (c[2] > 0) and (b < e):
			ind = x.index(s[b])
			b += 1
			c[ind] -= 1
			ans = min(ans, e - b + 1)
	if ans == int(1000000.0):
		print(0)
	else:
		print(ans)


t = int(input())
ans = [float('inf')] * t
for i in range(t):
	tempv = [0] * 3
	temp = 0
	s = input()
	n = len(s)
	for j in range(n):
		tempv[int(s[j]) - 1] = j + 1
		if tempv[0] * tempv[1] * tempv[2] > 1:
			temp = max(tempv) - min(tempv) + 1
			ans[i] = min(ans[i], temp)
		if ans[i] == 3:
			break
for i in range(t):
	if ans[i] == float('inf'):
		print(0)
	else:
		print(ans[i])


testCases = int(input())
for _ in range(testCases):
	s = input()
	distinct = set(s)
	if len(distinct) != 3:
		print(0)
	else:
		indexes = [-1, -1, -1]
		answer = len(s)
		for index in range(len(s)):
			if s[index] == '1':
				indexes[0] = index
			elif s[index] == '2':
				indexes[1] = index
			else:
				indexes[2] = index
			if -1 not in indexes:
				answer = min(answer, max(indexes) - min(indexes) + 1)
		print(answer)


for _ in range(int(input())):
	s = list(input())
	n = len(s)
	lis1 = [0] * 3
	l1 = r1 = 0
	ans = 10000000000
	while l1 < n and r1 < n:
		if min(lis1) != 0:
			a = int(s[l1]) - 1
			lis1[a] -= 1
			l1 += 1
		else:
			a = int(s[r1]) - 1
			lis1[a] += 1
			r1 += 1
		if min(lis1) != 0:
			ans = min(ans, r1 - l1)
	while l1 < n:
		a = int(s[l1]) - 1
		lis1[a] -= 1
		l1 += 1
		if min(lis1) != 0:
			ans = min(ans, r1 - l1)
	if ans == 10000000000:
		print(0)
	else:
		print(ans)


from sys import stdin, stdout

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

def SI():
	return stdin.readline()[:-1]
maxs = 200001
t = II()
for _ in range(t):
	s = SI()
	ans = maxs
	arr = [-1, -1, -1]
	for (i, c) in enumerate(s):
		val = int(c)
		arr[val - 1] = i
		minp = min(arr)
		maxp = max(arr)
		if minp > -1:
			l = maxp - minp + 1
			ans = min(ans, l)
	if ans == maxs:
		ans = 0
	stdout.write(str(ans) + '\n')


for _ in range(int(input())):
	x = input()
	j = len(x)
	li = [0, 0, 0, 0]
	ans = 3 * 10 ** 6
	if not x.count('1') or not x.count('2') or (not x.count('3')):
		print(0)
		continue
	for i in range(j):
		li[int(x[i])] = i + 1
		if li[1] and li[2] and li[3]:
			y = max(li[1:]) - min(li[1:])
			ans = min(ans, y + 1)
	print(ans)


from collections import Counter

def solve():
	s = input()
	(x, y, z) = (0, 0, 0)
	ans = len(s)
	f = False
	for i in range(0, len(s)):
		if s[i] == '1':
			x = i + 1
		if s[i] == '2':
			y = i + 1
		if s[i] == '3':
			z = i + 1
		if x > 0 and y > 0 and (z > 0):
			p = max(x, y, z)
			q = min(x, y, z)
			ans = min(ans, p - q + 1)
			f = True
	if f == True:
		print(ans)
	else:
		print(0)
t = int(input())
for i in range(0, t):
	solve()


from sys import stdin, stdout
from collections import defaultdict as df
import bisect
t = int(input())
for iii in range(t):
	s = stdin.readline().rstrip()
	sota = set()
	ans = float('inf')
	if s.count('1') == 0 or s.count('2') == 0 or s.count('3') == 0:
		print(0)
	else:
		d = df(list)
		for i in range(len(s)):
			d[s[i]].append(i)
			sota.add(s[i])
			if len(sota) == 3:
				sol = [d['1'][-1], d['2'][-1], d['3'][-1]]
				sol.sort()
				ans = min(ans, max(sol) - min(sol) + 1)
		stdout.write(str(ans))
		stdout.write(str('\n'))


import sys
for i in range(int(input())):
	s = input()
	last_1 = last_2 = last_3 = -1
	ans = sys.maxsize
	for i in range(len(s)):
		if s[i] == '1':
			last_1 = i
		elif s[i] == '2':
			last_2 = i
		elif s[i] == '3':
			last_3 = i
		if last_1 != -1 and last_2 != -1 and (last_3 != -1):
			a = min(last_1, last_2, last_3)
			b = max(last_1, last_2, last_3)
			ans = min(ans, b - a + 1)
	if ans != sys.maxsize:
		print(ans)
	else:
		print(0)


from collections import Counter

def solver(s):
	(x, y, z, n, flag) = (0, 0, 0, len(s), False)
	for i in range(len(s)):
		if s[i] == '1':
			x = i + 1
		if s[i] == '2':
			y = i + 1
		if s[i] == '3':
			z = i + 1
		if x > 0 and y > 0 and (z > 0):
			(p, q) = (max(x, y, z), min(x, y, z))
			(n, flag) = (min(n, p - q + 1), True)
	return n if flag else 0
for _ in range(int(input())):
	t = input()
	print(solver(t))


import math
import sys

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

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

def insr():
	s = input()
	return list(s[:len(s) - 1])

def invr():
	return map(int, input().split())
test_cases = int(input())
for _ in range(test_cases):
	string = str(input())
	len1 = len(string)
	pat = '123'
	len2 = len(pat)
	if len1 < len2:
		print(0)
		continue
	hash_pat = [0] * 256
	hash_str = [0] * 256
	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:
		print(0)
		continue
	print(len(string[start_index:start_index + min_len]))


t = int(input())
for test in range(t):
	arr = input()
	n = len(arr)
	last_one = -1
	last_two = -1
	last_three = -1
	lengths = set()
	for i in range(n):
		if arr[i] == '1':
			last_one = i
		elif arr[i] == '2':
			last_two = i
		else:
			last_three = i
		if last_one != -1 and last_two != -1 and (last_three != -1):
			sm = max(last_one, last_two, last_three) - min(last_one, last_two, last_three) + 1
			lengths.add(sm)
	if last_one == -1 or last_two == -1 or last_three == -1:
		print(0)
	else:
		print(min(lengths))


import sys
try:
	sys.stdin = open('Input.txt', 'r')
	sys.stdout = open('Output.txt', 'w')
except:
	pass
for testCases in range(int(input())):
	s = input()
	s1 = -1
	s2 = -1
	s3 = -1
	ans = float('inf')
	for i in range(len(s)):
		if s[i] == '1':
			s1 = i
		elif s[i] == '2':
			s2 = i
		else:
			s3 = i
		if s1 != -1 and s2 != -1 and (s3 != -1):
			ans = min(ans, max(s1, s2, s3) - min(s1, s2, s3) + 1)
	if ans == float('inf'):
		print(0)
	else:
		print(ans)


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('12+3')
	m2 = re.compile('13+2')
	m3 = re.compile('21+3')
	m4 = re.compile('23+1')
	m5 = re.compile('32+1')
	m6 = re.compile('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()


from collections import defaultdict

def findSubString(str):
	(n, count, start, min_len, dist_count) = (len(str), 0, 0, 10 ** 18, len(set([x for x in str])))
	curr_count = defaultdict(lambda : 0)
	for j in range(n):
		curr_count[str[j]] += 1
		if curr_count[str[j]] == 1:
			count += 1
		if count == dist_count:
			while curr_count[str[start]] > 1:
				if curr_count[str[start]] > 1:
					curr_count[str[start]] -= 1
				start += 1
			len_window = j - start + 1
			if min_len > len_window:
				min_len = len_window
	return min_len if dist_count == 3 else 0
t = int(input())
for q in range(t):
	n = input()
	print(findSubString(n))


for _ in range(int(input())):
	s = input()
	p1 = -1
	p2 = -1
	p3 = -1
	last = ' '
	length = 200000
	for i in range(len(s)):
		if s[i] == '1':
			p1 = i
		elif s[i] == '2':
			p2 = i
		else:
			p3 = i
		if last != s[i]:
			if p1 >= 0 and p2 >= 0 and (p3 >= 0):
				l = [p3, p1, p2]
				if length > max(l) - min(l):
					length = max(l) - min(l)
					if len == 2:
						break
		last = s[i]
	if p1 >= 0 and p2 >= 0 and (p3 >= 0):
		print(length + 1)
	else:
		print(0)


from collections import deque
from collections import OrderedDict
import math
import sys
import os
from io import BytesIO
import threading
import bisect
import heapq
from io import BytesIO, IOBase
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')
input = sys.stdin.readline

def fun(str1, f1, f2, f3, start, goto, step):
	for i in range(start, goto, step):
		if str1[i] == '1':
			f1[i] = i
			f2[i] = f2[i - step]
			f3[i] = f3[i - step]
		elif str1[i] == '2':
			f1[i] = f1[i - step]
			f2[i] = i
			f3[i] = f3[i - step]
		else:
			f1[i] = f1[i - step]
			f2[i] = f2[i - step]
			f3[i] = i
pass

def answer(cur, l, r, l1, r1):
	value1 = max(r - cur, r1 - cur)
	value2 = max(cur - l, cur - l1)
	value3 = r - cur + (cur - l1)
	value4 = cur - l + (r1 - cur)
	print(cur, value1, value2, value3, value4)
for t in range(int(input())):
	str1 = input()
	l1 = [0] * (len(str1) + 2)
	l2 = [0] * (len(str1) + 2)
	l3 = [0] * (len(str1) + 2)
	if str1.count('1') == 0 or str1.count('2') == 0 or str1.count('3') == 0:
		print(0)
		continue
	str1 = '0' + str1[0:len(str1) - 1]
	fi = 0
	li = 0
	minValue = 100000000
	fun(str1, l1, l2, l3, len(str1) - 1, 0, -1)
	for i in range(1, len(str1)):
		if l1[i] == 0 or l2[i] == 0 or l3[i] == 0:
			break
		if str1[i] == '1':
			value = max(l2[i] - i, l3[i] - i)
		elif str1[i] == '2':
			value = max(l1[i] - i, l3[i] - i)
		else:
			value = max(l1[i] - i, l2[i] - i)
		if minValue > value:
			minValue = value
			fi = i
			li = i + value + 1
	print(li - fi)


t = int(input())
for i in range(t):
	s = input()
	a = -1
	b = -1
	c = -1
	ans = 200000
	var = 0
	for j in range(len(s)):
		if s[j] == '1':
			a = j
		elif s[j] == '2':
			b = j
		elif s[j] == '3':
			c = j
		if a != -1 and b != -1 and (c != -1):
			li = sorted([a, b, c])
			var = li[2] - li[0]
			if var < ans:
				ans = var
				var = 0
	if ans == 200000:
		print('0')
	else:
		print(ans + 1)


t = int(input())
for _ in range(t):
	a = list(input())
	b = ['d'] * 3
	m = 0
	c = []
	if len(set(a)) == 3:
		for i in range(len(a)):
			if b[0] != 'd' and b[1] != 'd' and (b[2] != 'd'):
				m = max(b) - min(b) + 1
				c.append(m)
			if a[i] == '1':
				b[0] = i + 1
			elif a[i] == '2':
				b[1] = i + 1
			elif a[i] == '3':
				b[2] = i + 1
		if b[0] != 'd' and b[1] != 'd' and (b[2] != 'd'):
			m = max(b) - min(b) + 1
			c.append(m)
		print(min(c))
	else:
		print('0')


from collections import defaultdict
MAX_CHARS = 200000

def findSubString(str):
	n = len(str)
	dist_count = len(set([x for x in str]))
	count = 0
	start = 0
	min_len = 20000000000000000
	curr_count = defaultdict(lambda : 0)
	for j in range(n):
		curr_count[str[j]] += 1
		if curr_count[str[j]] == 1:
			count += 1
		if count == dist_count:
			while curr_count[str[start]] > 1:
				if curr_count[str[start]] > 1:
					curr_count[str[start]] -= 1
				start += 1
			len_window = j - start + 1
			if min_len > len_window:
				min_len = len_window
				start_index = start
	return str[start_index:start_index + min_len]
T = int(input())
for _ in range(T):
	S = input()
	if '1' in S and '2' in S and ('3' in S):
		print(len(findSubString(S)))
	else:
		print(0)


for _ in range(int(input())):
	s = input()
	(count, start) = (1, 0)
	d = []
	c = []
	for i in range(1, len(s)):
		if s[i] == s[i - 1]:
			count += 1
		if s[i] != s[i - 1]:
			d.append([start, i - 1])
			start = i
			count = 0
	if len(d) == 0:
		print(0)
		continue
	e = d[len(d) - 1][1]
	d.append([e + 1, e + 1 + count])
	f = []
	for i in range(1, len(d) - 1):
		(x, y, z) = (s[d[i][0] - 1], s[d[i][0]], s[d[i][1] + 1])
		f.append(x)
		f.append(y)
		f.append(z)
		if len(set(f)) == 3:
			c.append(d[i][1] - d[i][0] + 3)
		f = []
	if len(c) == 0:
		print(0)
		continue
	print(min(c))


from collections import defaultdict
import sys
T = int(input())

def solve(s):
	t = '123'
	if len(t) > len(s):
		return 0
	hashmap = defaultdict(int)
	for ch in t:
		hashmap[ch] += 1
	start = 0
	end = 0
	count = len(hashmap)
	mwl = sys.maxsize
	smw = start
	while end < len(s):
		ch = s[end]
		if ch in hashmap:
			hashmap[ch] -= 1
			if hashmap[ch] == 0:
				count -= 1
		end += 1
		while count == 0:
			ch = s[start]
			if ch in hashmap:
				hashmap[ch] += 1
				if hashmap[ch] > 0:
					count += 1
					if mwl > end - start:
						mwl = end - start
						smw = start
			start += 1
	if mwl == sys.maxsize:
		return 0
	return len(s[smw:smw + mwl])
while T != 0:
	T -= 1
	a = input()
	a = list(a)
	answer = solve(a)
	print(answer)


for _ in range(int(input())):
	a = input()
	ones = -1
	twos = -1
	three = -1
	ans = 2000000
	for i in range(len(a)):
		if a[i] == '1':
			ones = i
		elif a[i] == '2':
			twos = i
		else:
			three = i
		if ones != -1 and twos != -1 and (three != -1):
			if ans > max(ones, twos, three) - min(ones, twos, three) + 1:
				ans = max(ones, twos, three) - min(ones, twos, three) + 1
	if ones != -1 and twos != -1 and (three != -1):
		print(ans)
	else:
		print(0)


for s in [*open(0)][1:]:
	i = 1
	m = r = 4 ** 9
	a = [-m] * 7
	for d in map(int, s[:-1]):
		a[d] = i
		i += 1
		r = min(r, i - a[7 - d])
		for k in {1, 2, 3} - {d}:
			a[d + k + 1] = a[k]
	print((r < m) * r)


import sys
from math import ceil, sqrt
read = sys.stdin.buffer.readline
import heapq
mi = lambda : map(int, read().split())
li = lambda : list(mi())
cin = lambda : int(read())

def isp(n):
	i = 2
	while i * i <= n:
		if n % i == 0:
			return False
		i += 1
	return True
primes = []
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 _ in range(cin()):
	s = input()
	ans = findSubString(s, '123')
	if ans == '':
		print(0)
	else:
		print(len(ans))


for _ in range(int(input())):
	m = 0
	a = input()
	(one, two, three) = (-1, -1, -1)
	n = len(a) + 1
	for i in range(len(a)):
		if a[i] == '1':
			one = i
		elif a[i] == '2':
			two = i
		else:
			three = i
		if one >= 0 and two >= 0 and (three >= 0):
			f = max([one, two, three]) - min([one, two, three]) + 1
			if f < n:
				n = f
				m = 1
		if n == 3:
			break
	if m == 0:
		print(0)
	else:
		print(n)


T = int(input())
for t in range(T):
	S = input()
	N = len(S)
	ans = N
	hash = {}
	cnt = 0
	j = 0
	found = False
	for i in range(N):
		hash[S[i]] = hash.get(S[i], 0) + 1
		if hash[S[i]] == 1:
			cnt += 1
		if cnt == 3:
			found = True
			ans = min(ans, i - j + 1)
			while j < i and cnt == 3:
				hash[S[j]] -= 1
				if hash[S[j]] == 0:
					cnt -= 1
				else:
					ans = min(ans, i - j)
				j += 1
	if not found:
		ans = 0
	print(ans)


import sys, os, io

def rs():
	return sys.stdin.readline().rstrip()

def ri():
	return int(sys.stdin.readline())

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

def ws(s):
	sys.stdout.write(s + '\n')

def wi(n):
	sys.stdout.write(str(n) + '\n')

def wia(a):
	sys.stdout.write(' '.join([str(x) for x in a]) + '\n')
import math
from collections import deque
import collections

def main():
	for _ in range(int(input())):
		s = rs()
		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:
			wi(0)
		else:
			wi(m)

class FastReader(io.IOBase):
	newlines = 0

	def __init__(self, fd, chunk_size=1024 * 8):
		self._fd = fd
		self._chunk_size = chunk_size
		self.buffer = io.BytesIO()

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size))
			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, size=-1):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size if size == -1 else size))
			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()

class FastWriter(io.IOBase):

	def __init__(self, fd):
		self._fd = fd
		self.buffer = io.BytesIO()
		self.write = self.buffer.write

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

class FastStdin(io.IOBase):

	def __init__(self, fd=0):
		self.buffer = FastReader(fd)
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

class FastStdout(io.IOBase):

	def __init__(self, fd=1):
		self.buffer = FastWriter(fd)
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.flush = self.buffer.flush
sys.stdin = FastStdin()
sys.stdout = FastStdout()
main()


import sys
import math as mt
import bisect
t = int(input())
for __ in range(t):
	s = input()
	o = -1
	t = -1
	th = -1
	n = len(s)
	ans = n + 1
	for i in range(len(s)):
		if s[i] == '1':
			o = i
		elif s[i] == '2':
			t = i
		else:
			th = i
		if o != -1 and t != -1 and (th != -1):
			maxi = max(o, t, th)
			mini = min(o, t, th)
			ans = min(ans, maxi - mini + 1)
	if ans == n + 1:
		print(0)
	else:
		print(ans)


def sol(s):
	c1 = c2 = c3 = 0
	N = len(s)
	j = 0
	flag = False
	while j < N:
		if s[j] == '1':
			c1 += 1
		elif s[j] == '2':
			c2 += 1
		else:
			c3 += 1
		if c1 > 0 and c2 > 0 and (c3 > 0):
			flag = True
			break
		j += 1
	if not flag:
		return 0
	ans = j + 1
	i = 0
	while True:
		while True:
			if s[i] == '1' and c1 > 1:
				c1 -= 1
				i += 1
			elif s[i] == '2' and c2 > 1:
				c2 -= 1
				i += 1
			elif s[i] == '3' and c3 > 1:
				c3 -= 1
				i += 1
			else:
				break
		cur = j - i + 1
		if cur < ans:
			ans = cur
		j += 1
		if j == N:
			break
		if s[j] == '1':
			c1 += 1
		elif s[j] == '2':
			c2 += 1
		else:
			c3 += 1
	return ans
n = int(input())
while n > 0:
	ans = sol(input())
	print(ans)
	n -= 1


from collections import *
for _ in range(int(input())):
	l = [int(i) for i in input()]
	dic = {}
	n = len(l)
	flag = False
	ans = 10 ** 6
	for i in range(n):
		dic[l[i]] = i
		if len(dic) == 3:
			flag = True
			val = list(dic.values())
			ans = min(ans, max(val) - min(val) + 1)
	if flag:
		print(ans)
	else:
		print(0)


import sys

def hasAll(st):
	l = set(map(lambda x: x[0], st))
	return '1' in l and '2' in l and ('3' in l)
[T] = input().split()
T = int(T)
for case in range(T):
	[s] = input().split()
	if '1' not in s or '2' not in s or '3' not in s:
		print(0)
		continue
	n = len(s)
	segments = []
	acc = 0
	for i in range(n - 1):
		acc += 1
		if s[i] != s[i + 1]:
			segments.append((s[i], acc))
			acc = 0
	segments.append((s[-1], acc + 1))
	n = len(segments)
	mi = None
	for k in range(0, n - 2):
		if hasAll(segments[k:k + 3]):
			sumCost = 2 + segments[k + 1][1]
			if mi != None:
				mi = min(sumCost, mi)
			else:
				mi = sumCost
	print(mi)


import sys
input = lambda : sys.stdin.readline().strip('\r\n')
for _ in range(int(input())):
	s = [int(x) for x in input()]
	n = len(s)
	ans = float('inf')
	one = -1
	two = -1
	three = -1
	for i in range(n):
		if s[i] == 1:
			one = i
		elif s[i] == 2:
			two = i
		elif s[i] == 3:
			three = i
		if one != -1 and two != -1 and (three != -1):
			ans = min(ans, max(one, two, three) - min(one, two, three) + 1)
	if one == -1 or two == -1 or three == -1:
		print(0)
	else:
		print(ans)


for t in range(int(input())):
	s = str(input())
	l = len(s)
	items = [-1] * 3
	m = float('inf')
	for i in range(l):
		items[int(s[i]) - 1] = i
		if -1 not in items:
			m = min(m, max(items) - min(items) + 1)
	m = 0 if m == float('inf') else m
	print(m)


def find_shortest_contiguous_substring(string):
	i = 0
	j = 0
	contains_three = False
	min_length = -1
	character_counts = {'1': 0, '2': 0, '3': 0}
	while i <= j and j <= len(string):
		if contains_three:
			character_counts[string[i]] -= 1
			i += 1
		else:
			if j >= len(string):
				break
			character_counts[string[j]] += 1
			j += 1
		if character_counts['1'] > 0 and character_counts['2'] > 0 and (character_counts['3'] > 0):
			contains_three = True
			if min_length == -1 or j - i < min_length:
				min_length = j - i
		else:
			contains_three = False
	return min_length if min_length != -1 else 0
for _ in range(int(input())):
	string = input()
	print(find_shortest_contiguous_substring(string))


test = int(input())
for i in range(test):
	s = input()
	l = 0
	dis = len(s) + 1
	char = {'1': 0, '2': 0, '3': 0}
	for i in range(len(s)):
		char[s[i]] += 1
		while all((t > 0 for t in char.values())):
			dis = min(dis, i - l + 1)
			char[s[l]] -= 1
			l += 1
	print(dis) if dis <= len(s) else print(0)


def re(l):
	return max(l) - min(l) + 1
for _ in range(int(input())):
	s = input()
	if '1' not in s or '2' not in s or '3' not in s:
		print(0)
		continue
	d = [-1] * 3
	val = 0
	miny = 99999999
	for i in range(len(s)):
		d[int(s[i]) - 1] = i
		if min(d) != -1:
			val = re(d)
			miny = min(miny, val)
		if val == 3:
			break
	print(miny)


from sys import stdin
inp = stdin.readline
t = int(inp().strip())
while t:
	t -= 1
	n = inp().strip()
	(lastOne, lastTwo, LastThree) = (-1, -1, -1)
	bestLength = -1
	for (i, char) in enumerate(n):
		if char == '1':
			lastOne = i
			if not (lastOne == -1 or lastTwo == -1 or LastThree == -1):
				temp = max(i, lastTwo, LastThree) - min(i, lastTwo, LastThree)
				if bestLength >= temp or bestLength == -1:
					bestLength = temp
		elif char == '2':
			lastTwo = i
			if not (lastOne == -1 or lastTwo == -1 or LastThree == -1):
				temp = max(lastOne, i, LastThree) - min(lastOne, i, LastThree)
				if bestLength >= temp or bestLength == -1:
					bestLength = temp
		else:
			LastThree = i
			if not (lastOne == -1 or lastTwo == -1 or LastThree == -1):
				temp = max(lastOne, lastTwo, i) - min(lastOne, lastTwo, i)
				if bestLength >= temp or bestLength == -1:
					bestLength = temp
	if bestLength == -1:
		print(0)
	else:
		print(bestLength + 1)


from collections import defaultdict
for _ in range(int(input())):
	s = input()
	d = defaultdict(int)
	ans = 10 ** 9
	(i, j) = (0, 0)
	while j < len(s):
		d[s[j]] += 1
		while len(d) == 3:
			ans = min(ans, j - i + 1)
			d[s[i]] -= 1
			if d[s[i]] <= 0:
				del d[s[i]]
			i += 1
		j += 1
	if ans == 10 ** 9:
		ans = 0
	print(ans)


t = int(input())
for x in range(t):
	p = [-1, -1, -1]
	s = input()
	n = len(s)
	if s.count('1') == 0 or s.count('2') == 0 or s.count('3') == 0:
		n = 0
	for i in range(len(s)):
		p[int(s[i]) - 1] = i
		if p[0] != -1 and p[1] != -1 and (p[2] != -1):
			n = min(n, max(p[0], p[1], p[2]) - min(p[0], p[1], p[2]) + 1)
	print(n)


t = int(input())
for _ in range(t):
	n = input()
	x = 0
	a = []
	for i in range(1, len(n)):
		if n[i] == n[i - 1]:
			continue
		else:
			a.append(n[x:i])
			x = i
	if len(a) > 0:
		if n[-1] == a[-1][0]:
			a[-1][0] += n[-1]
		else:
			a.append(n[-1])
	ans = float('inf')
	for i in range(len(a) - 2):
		if int(a[i][0]) + int(a[i + 1][0]) + int(a[i + 2][0]) == 6:
			if len(a[i + 1]) == 1:
				ans = 3
				break
			elif len(a[i + 1]) + 2 < ans:
				ans = len(a[i + 1]) + 2
	if ans == float('inf'):
		print(0)
	else:
		print(ans)


import sys

def read_integer():
	return int(sys.stdin.readline())

def read_integers():
	return [int(x) for x in sys.stdin.readline().split(' ')]

def print_integers(nums):
	print(' '.join([str(x) for x in nums]))

def func():
	s = sys.stdin.readline()[:-1]
	if '1' not in s or '2' not in s or '3' not in s:
		return 0
	l = 0
	times = {'1': 0, '2': 0, '3': 0}
	ans = len(s)
	for r in range(len(s)):
		times[s[r]] += 1
		while times[s[l]] > 1:
			times[s[l]] -= 1
			l += 1
		if times['1'] > 0 and times['2'] > 0 and (times['3'] > 0):
			ans = min(ans, r - l + 1)
	return ans
nt = read_integer()
for _ in range(nt):
	print(func())


import math
import collections
from sys import stdin, stdout, setrecursionlimit
import bisect as bs
T = int(stdin.readline())
for _ in range(T):
	a = stdin.readline().strip('\n')
	d = {}
	n = len(a)
	mn = n + 1
	s = 0
	e = -1
	while e < n:
		if len(d) != 3:
			e = e + 1
			if e < n:
				if a[e] not in d:
					d[a[e]] = 0
				d[a[e]] += 1
		else:
			if e - s + 1 < mn:
				mn = e - s + 1
			d[a[s]] -= 1
			if d[a[s]] == 0:
				del d[a[s]]
			s += 1
	print(mn if mn != n + 1 else 0)


from collections import Counter
from collections import defaultdict
from collections import deque
import math
import heapq
import sys
input = sys.stdin.readline
import bisect
rs = lambda : input().strip()
ri = lambda : int(input())
rl = lambda : list(map(int, input().split()))
rls = lambda : list(map(str, input().split()))
t = int(input())
for _ in range(0, t):
	s = list(input().strip())
	s = list(map(int, s))
	s.append(0)
	n = len(s)
	if len(s) - 1 < 3:
		print(0)
		continue
	d = defaultdict(lambda : 0)
	i = 0
	j = 2
	d[s[0]] += 1
	d[s[1]] += 1
	mn = 9999999999999
	while j < n and i < n:
		if d[1] >= 1 and d[2] >= 1 and (d[3] >= 1):
			if j - i < mn:
				mn = j - i
			d[s[i]] = d[s[i]] - 1
			i = i + 1
		else:
			d[s[j]] += 1
			j = j + 1
	if mn == 9999999999999:
		print(0)
	else:
		print(mn)


import sys
for _ in range(int(input())):
	s = input()
	a = -1
	b = -1
	c = -1
	m = sys.maxsize
	for i in range(len(s)):
		if s[i] == '1':
			a = i
		elif s[i] == '2':
			b = i
		elif s[i] == '3':
			c = i
		u = min(a, b, c)
		v = max(a, b, c)
		if u != -1:
			r = v - u + 1
			if r < m:
				m = r
			if a == u:
				a = -1
			elif b == u:
				b = -1
			elif c == u:
				c = -1
	if m == sys.maxsize:
		print(0)
	else:
		print(m)


t = int(input())
while t > 0:
	s = input()
	one = -1
	two = -1
	three = -1
	final = []
	for i in range(len(s)):
		if s[i] == '1':
			one = i
		elif s[i] == '2':
			two = i
		else:
			three = i
		if one != -1 and two != -1 and (three != -1):
			lis = []
			lis.append(one)
			lis.append(two)
			lis.append(three)
			mini = min(lis)
			maxi = max(lis)
			final.append(maxi - mini + 1)
	if one == -1 or two == -1 or three == -1:
		print('0')
	else:
		print(min(final))
	t -= 1


t = int(input())
for _ in range(t):
	s = input()
	ans = len(s) + 1
	count = [0, 0, 0]
	(i, j) = (0, 0)
	while i < len(s) and j < len(s):
		if i == j:
			count[int(s[i]) - 1] += 1
		else:
			count[int(s[j]) - 1] += 1
		if count[0] >= 1 and count[1] >= 1 and (count[2] >= 1):
			while i < j and count[int(s[i]) - 1] > 1:
				i += 1
				count[int(s[i - 1]) - 1] -= 1
			ans = min(ans, j - i + 1)
		j += 1
	if ans == len(s) + 1:
		print(0)
	else:
		print(ans)


from math import *
from collections import *
from itertools import *
from bisect import *
from heapq import *
from operator import *
from sys import *
setrecursionlimit(1000000)
d = defaultdict(lambda : 0, {})

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

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

def o():
	return int(input())

def r(x):
	return range(len(x))

def mk(a, b):
	if a > b:
		return (b, a)
	else:
		return (a, b)

def kl(con, x=0):
	if x == 0:
		print('Yes') if con else print('No')
	elif x == 1:
		print('yes') if con else print('no')
	elif x == 2:
		print('YES') if con else print('NO')
MOD = 1000000007
MAX = float('inf')
MIN = -float('inf')
p = input
for _ in range(o()):
	s = p()
	l = []
	fg = 1
	c = 1
	c1 = s[0]
	ap = l.append
	for i in range(1, len(s)):
		if s[i] == s[i - 1]:
			c += 1
			c1 = s[i]
			fg = 1
		elif fg == 1 or c == 1:
			ap((int(c1), c))
			c = 1
			c1 = s[i]
			fg = 0
	if fg == 1 or c == 1:
		ap((int(c1), c))
	ans = MAX
	for i in range(1, len(l) - 1):
		t = [l[i][0], l[i + 1][0], l[i - 1][0]]
		if set(t) == {1, 2, 3}:
			ans = min(ans, l[i][1] + 2)
	if ans == MAX:
		ans = 0
	print(ans)


from sys import stdin

def solve(s):
	lp = 0
	c = [0, 0, 0, 0]
	v = 2000000
	for i in range(len(s)):
		c[ord(s[i]) - ord('0')] += 1
		while c[1] > 0 and c[2] > 0 and (c[3] > 0):
			v = min(v, i - lp + 1)
			c[ord(s[lp]) - ord('0')] -= 1
			lp += 1
	if v == 2000000:
		print(0)
	else:
		print(v)
	return

def main():
	inp = stdin.readline
	for _ in range(int(inp())):
		s = inp().strip()
		solve(s)
main()


import re
t = int(input())
pattern = ['12+3', '32+1', '21+3', '31+2', '13+2', '23+1']
for _ in range(t):
	s = input()
	L = []
	for p in pattern:
		L = L + re.findall(p, s)
	M = [len(k) for k in L]
	if M == []:
		print(0)
	else:
		print(min(M))


for i in range(int(input())):
	a = list(str(input()))
	n = []
	l = [-2, -2, -2]
	for i in range(0, len(a)):
		if a[i] == '1':
			l[0] = i
		elif a[i] == '2':
			l[1] = i
		elif a[i] == '3':
			l[2] = i
		if -2 not in l:
			n.append(max(l) - min(l) + 1)
	n.sort()
	if n == []:
		print(0)
	else:
		print(n[0])


for t in range(int(input())):
	s = input()
	if len(set(s)) != 3:
		print(0)
	else:
		fc = [s[0], 0]
		sc = list()
		tc = list()
		ans = -1
		flag = False
		for i in range(1, len(s)):
			if fc[0] == s[i]:
				fc = [s[i], i]
			elif len(sc) == 0:
				sc = [s[i], i]
			elif sc[0] == s[i]:
				sc = [s[i], i]
			else:
				tc = [s[i], i]
				flag = True
			if ans == -1 and flag:
				ans = max([fc[1], sc[1], tc[1]]) + 1 - min([fc[1], sc[1], tc[1]])
			elif flag:
				ans = min(ans, max([fc[1], sc[1], tc[1]]) + 1 - min([fc[1], sc[1], tc[1]]))
		print(ans)


from sys import stdin
inp = lambda : stdin.readline().strip()
t = int(inp())
for _ in range(t):
	n = inp()
	last1 = -1
	last2 = -1
	last3 = -1
	ans = 200001
	for i in range(len(n)):
		if n[i] == '1':
			last1 = i
		elif n[i] == '2':
			last2 = i
		elif n[i] == '3':
			last3 = i
		if last1 == -1 or last2 == -1 or last3 == -1:
			continue
		ans = min(ans, max(last2, last1, last3) - min(last2, last1, last3))
	if ans == 200001:
		print(0)
	else:
		print(ans + 1)


from bisect import bisect_left, bisect_right
for _ in range(int(input())):
	s = input()
	if len(set(s)) != 3:
		print(0)
		continue
	n = len(s)
	(a, b, c) = ([0], [0], [0])
	for i in range(n):
		a.append(a[-1])
		b.append(b[-1])
		c.append(c[-1])
		if s[i] == '1':
			a[-1] += 1
		elif s[i] == '2':
			b[-1] += 1
		else:
			c[-1] += 1
	ans = n
	for i in range(n + 1):
		if a[i] * b[i] * c[i]:
			j = bisect_left(a, a[i])
			k = bisect_left(b, b[i])
			l = bisect_left(c, c[i])
			m = min(j, k, l)
			ans = min(ans, i - m + 1)
	print(ans)


import re
for t in range(int(input())):
	x = input()
	log = 0
	for i in '123':
		if i not in x:
			log = 1
			print(0)
			break
	if log == 0:
		ans = len(x)
		p = re.compile('1+|2+|3+')
		for i in re.finditer(p, x):
			s = i.start()
			e = i.end()
			if s > 0 and e < len(x):
				if x[s - 1] != x[e]:
					l = e - s + 2
					if l < ans:
						ans = l
		print(ans)


from sys import stdin, stdout
t = int(input())
for _ in range(t):
	s = stdin.readline().strip()
	d = {'1': 0, '2': 0, '3': 0}
	start = end = 0
	minlen = 2 * 10 ** 6
	while end < len(s):
		if minlen == 3:
			break
		if all(d.values()):
			while all(d.values()):
				d[s[start]] -= 1
				start = start + 1
				minlen = min(minlen, end - start + 1)
		else:
			if end < len(s):
				d[s[end]] += 1
			end += 1
	if all(d.values()):
		while all(d.values()):
			d[s[start]] -= 1
			start = start + 1
			minlen = min(minlen, end - start + 1)
	print(0 if minlen == 2 * 10 ** 6 else minlen)


import sys
cases = int(input())
for t in range(cases):
	s = input()
	(a, b, c) = (-sys.maxsize, -sys.maxsize, -sys.maxsize)
	l = sys.maxsize
	p = 0
	d = {'1': a, '2': b, '3': c}
	for i in s:
		d[i] = p
		v = min(d.values())
		l = min(l, 1 + p - v)
		p += 1
	if l > 200000:
		l = 0
	print(l)


def solution():
	for _ in range(int(input())):
		s = input()
		d = {}
		m = len(s)
		for i in range(len(s)):
			d[s[i]] = i
			if len(d) == 3:
				m = min(m, max(d.values()) - min(d.values()) + 1)
		if len(d) != 3:
			print(0)
		else:
			print(m)
solution()


import sys

def input():
	return sys.stdin.readline()
t = int(input())
answers = []
for _ in range(t):
	s = input()
	s = s.split()[0]
	vals = [int(i) - 1 for i in s]
	best = float('inf')
	left = 0
	right = -1
	current = [0, 0, 0]
	current = [0, 0, 0]
	while True:
		if current[0] < 1 or current[1] < 1 or current[2] < 1:
			right += 1
			if right >= len(vals):
				break
			current[vals[right]] += 1
		else:
			best = min(best, right - left + 1)
			current[vals[left]] -= 1
			left += 1
	if best == float('inf'):
		answers.append(0)
	else:
		answers.append(best)
print(*answers, sep='\n')


import sys

def get_ints():
	return map(int, sys.stdin.readline().split())
for _ in range(int(input())):
	s = input()
	(one, two, three) = (-1, -1, -1)
	n = len(s)
	ans = n + 1
	for i in range(n):
		if s[i] == '1':
			one = i
		elif s[i] == '2':
			two = i
		elif s[i] == '3':
			three = i
		if one > -1 and two > -1 and (three > -1):
			ans = min(ans, max(one, two, three) - min(one, two, three) + 1)
	if ans != n + 1:
		print(ans)
	else:
		print(0)


t = int(input())
for _ in range(t):
	s = input()
	inf = 1000000000
	i = -1
	j = -1
	k = -1
	ans = inf
	for (idx, val) in enumerate(s):
		if val == '1':
			i = idx
		if val == '2':
			j = idx
		if val == '3':
			k = idx
		if i > -1 and j > -1 and (k > -1):
			ans = min(ans, max(i, j, k) - min(i, j, k) + 1)
	answer = ans if ans < inf else 0
	print(answer)


for _ in range(int(input())):
	n = input()
	res = 200000000000000
	l = len(n)
	if l < 3:
		print(0)
		continue
	a = b = c = -1
	if n.find('1') == -1:
		print(0)
		continue
	if n.find('2') == -1:
		print(0)
		continue
	if n.find('3') == -1:
		print(0)
		continue
	s = set(())
	for i in range(l):
		s.add(n[i])
		if n[i] == '1':
			a = i
		elif n[i] == '2':
			b = i
		elif n[i] == '3':
			c = i
		if len(s) == 3:
			y = min(c, min(a, b))
			x = max(c, max(a, b))
			p = x - y + 1
			res = min(res, p)
	print(res)


def triple(n):
	points = [-1, -1, -1]
	result = []
	for i in range(len(n)):
		if points[0] != -1 and points[1] != -1 and (points[2] != -1):
			result.append(max(points) - min(points) + 1)
		if n[i] == '1':
			points[0] = i
		if n[i] == '2':
			points[1] = i
		if n[i] == '3':
			points[2] = i
	if points[0] != -1 and points[1] != -1 and (points[2] != -1):
		result.append(max(points) - min(points) + 1)
	if len(result) == 0:
		return 0
	else:
		return min(result)
for i in range(int(input().strip())):
	print(triple(input().strip()))


import atexit
import io
import sys
from collections import defaultdict
_INPUT_LINES = sys.stdin.read().splitlines()
input = iter(_INPUT_LINES).__next__
_OUTPUT_BUFFER = io.StringIO()
sys.stdout = _OUTPUT_BUFFER

@atexit.register
def write():
	sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())

def substring_triplet(in_str):
	first = 0
	last = 0
	set_substr = set(in_str[first])
	min_substr_len = len(in_str)
	once = False
	for i in range(1, len(in_str)):
		set_substr.add(in_str[i])
		last = i
		if in_str[first] == in_str[last]:
			if last - first > 1:
				first = last - 1
			else:
				first = last
			set_substr = set(in_str[first:last + 1])
		if len(set_substr) == 3:
			once = True
			min_substr_len = min(min_substr_len, last - first + 1)
			first = last - 1
			set_substr = set(in_str[first:last + 1])
	return min_substr_len if once else 0
iters = int(input())
for i in range(iters):
	in_str = input()
	print(substring_triplet(in_str))


from sys import stdin

def main():
	input = lambda : stdin.readline()[:-1]
	T = int(input())
	for _ in [0] * T:
		S = input()
		nums = [0] * 4
		ans = float('inf')
		(j, n) = (0, len(S))
		for i in range(n):
			if i:
				nums[int(S[i - 1])] -= 1
			if all(nums[1:]):
				ans = min(ans, sum(nums[1:]))
				continue
			while j < n:
				nums[int(S[j])] += 1
				if all(nums[1:]):
					ans = min(ans, sum(nums[1:]))
					j += 1
					break
				j += 1
		print(0 if ans == float('inf') else ans)
main()


for _ in range(int(input())):
	s = input()
	all_ = set(s)
	if len(all_) < 3:
		print(0)
	elif len(all_) == len(s):
		print(3)
	else:
		l = len(s)
		i = 0
		total = l
		while i < l - 2:
			start = i
			a = s[i]
			cur_alphas = {a}
			for j in range(i + 1, l):
				if s[j] == a:
					if len(cur_alphas) == 2:
						i = j - 1
					else:
						i = j
					break
				elif len(cur_alphas) == 1:
					b = s[j]
					cur_alphas.add(b)
				elif len(cur_alphas) == 2:
					if s[j] not in cur_alphas:
						end = j
						if total > end - start + 1:
							total = end - start + 1
						if total == 3:
							i = l
							break
						i = j - 1
						break
				if j == l - 1:
					i = l
					break
		print(total)


kl = int(input())
for l in range(kl):
	s = input()
	n = len(s)
	if set(s) != {'1', '2', '3'}:
		print(0)
		continue
	s = 'a' + s
	(p1, p2, dl) = (0, 0, n + 1)
	for i in range(1, n + 1):
		if s[i] == '3':
			p1 = i
			if p2:
				dl = min(dl, i - p2 + 1)
		if {s[i], s[i - 1]} == {'1', '2'}:
			p2 = i - 1
			if p1:
				dl = min(dl, i - p1 + 1)
	(p1, p2) = (0, 0)
	for i in range(1, n + 1):
		if s[i] == '2':
			p1 = i
			if p2:
				dl = min(dl, i - p2 + 1)
		if {s[i], s[i - 1]} == {'1', '3'}:
			p2 = i - 1
			if p1:
				dl = min(dl, i - p1 + 1)
	(p1, p2) = (0, 0)
	for i in range(1, n + 1):
		if s[i] == '1':
			p1 = i
			if p2:
				dl = min(dl, i - p2 + 1)
		if {s[i], s[i - 1]} == {'3', '2'}:
			p2 = i - 1
			if p1:
				dl = min(dl, i - p1 + 1)
	print(dl)


for t in range(int(input())):
	a = input()
	a1 = a2 = a3 = -1
	k = 0
	for i in range(len(a)):
		if a[i] == '1':
			a1 = i
			if a2 >= 0 and a3 >= 0:
				c = i - min(a2, a3) + 1
				if c < k or k == 0:
					k = c
		elif a[i] == '2':
			a2 = i
			if a1 >= 0 and a3 >= 0:
				c = i - min(a1, a3) + 1
				if c < k or k == 0:
					k = c
		else:
			a3 = i
			if a2 >= 0 and a1 >= 0:
				c = i - min(a2, a1) + 1
				if c < k or k == 0:
					k = c
	print(k)


import sys
import math
import os
import itertools
import string
import heapq
import _collections
from collections import Counter
from collections import defaultdict
from functools import lru_cache
import bisect
import re
import queue
from decimal import *

class Scanner:

	@staticmethod
	def int():
		return int(sys.stdin.readline().rstrip())

	@staticmethod
	def string():
		return sys.stdin.readline().rstrip()

	@staticmethod
	def map_int():
		return [int(x) for x in Scanner.string().split()]

	@staticmethod
	def string_list(n):
		return [Scanner.string() for i in range(n)]

	@staticmethod
	def int_list_list(n):
		return [Scanner.map_int() for i in range(n)]

	@staticmethod
	def int_cols_list(n):
		return [Scanner.int() for i in range(n)]

class Math:

	@staticmethod
	def gcd(a, b):
		if b == 0:
			return a
		return Math.gcd(b, a % b)

	@staticmethod
	def lcm(a, b):
		return a * b // Math.gcd(a, b)

	@staticmethod
	def divisor(n):
		res = []
		i = 1
		for i in range(1, int(n ** 0.5) + 1):
			if n % i == 0:
				res.append(i)
				if i != n // i:
					res.append(n // i)
		return res

	@staticmethod
	def round_up(a, b):
		return -(-a // b)

	@staticmethod
	def is_prime(n):
		if n < 2:
			return False
		if n == 2:
			return True
		if n % 2 == 0:
			return False
		d = int(n ** 0.5) + 1
		for i in range(3, d + 1, 2):
			if n % i == 0:
				return False
		return True

def pop_count(x):
	x = x - (x >> 1 & 6148914691236517205)
	x = (x & 3689348814741910323) + (x >> 2 & 3689348814741910323)
	x = x + (x >> 4) & 1085102592571150095
	x = x + (x >> 8)
	x = x + (x >> 16)
	x = x + (x >> 32)
	return x & 127
MOD = int(1000000000.0) + 7
INF = int(1000000000000000.0)

def solve():
	S = Scanner.string()
	if not '1' in S or not '2' in S or (not '3' in S):
		print(0)
		return
	ans = INF
	M = {'1': -1, '2': -1, '3': -1}
	for (i, s) in enumerate(S):
		M[s] = i
		if -1 in M.values():
			continue
		ans = min(ans, max(M.values()) - min(M.values()) + 1)
	ans = min(ans, max(M.values()) - min(M.values()) + 1)
	print(ans)

def main():
	T = Scanner.int()
	for _ in range(T):
		solve()
main()


for _ in range(int(input())):
	list1 = list(map(int, input()))
	c1 = 0
	c2 = 0
	c3 = 0
	s = len(list1)
	j1 = 0
	j2 = 0
	j3 = 0
	f = 0
	for i in range(len(list1)):
		if list1[i] == 1:
			c1 += 1
			j1 = i
		if list1[i] == 2:
			c2 += 1
			j2 = i
		if list1[i] == 3:
			c3 += 1
			j3 = i
		if c1 > 0 and c2 > 0 and (c3 > 0):
			m1 = min(j1, j2, j3)
			m2 = max(j1, j2, j3)
			m = m2 - m1 + 1
			if m <= s:
				s = m
				f = 1
	if f == 1:
		print(s)
	else:
		print(0)


import sys
readline = sys.stdin.readline

def solve():
	S = readline().strip()
	S = [int(v) - 1 for v in S]
	counts = [0, 0, 0]
	ans = 1e+18
	tail = 0
	for (i, c) in enumerate(S):
		counts[c] += 1
		while True:
			if counts[S[tail]] > 1:
				counts[S[tail]] -= 1
				tail += 1
			else:
				break
		if all((v > 0 for v in counts)):
			ans = min(ans, i - tail + 1)
	if ans != 1e+18:
		print(ans)
	else:
		print(0)
T = int(readline())
for i in range(T):
	solve()


t = int(input())
for _ in range(t):
	s = input()
	n = len(s)
	l = []
	cnt = 1
	for i in range(n - 1):
		if s[i] != s[i + 1]:
			l.append((s[i], cnt))
			cnt = 1
		else:
			cnt += 1
	l.append((s[-1], cnt))
	ans = float('inf')
	for i in range(len(l) - 2):
		if l[i][0] != l[i + 2][0]:
			ans = min(ans, l[i + 1][1] + 2)
	if ans == float('inf'):
		print(0)
	else:
		print(ans)


for _ in range(int(input())):
	s = input()
	len1 = len(s)
	p1 = -1
	p2 = -1
	p3 = -1
	for i in range(len1):
		if s[i] == '1':
			p1 = i
		if s[i] == '2':
			p2 = i
		if s[i] == '3':
			p3 = i
		if p1 >= 0 and p2 >= 0 and (p3 >= 0):
			temp = max(p1, p2, p3) - min(p1, p2, p3)
			if len1 > temp:
				len1 = temp
	if p1 >= 0 and p2 >= 0 and (p3 >= 0):
		print(len1 + 1)
	else:
		print(0)


def solve(string):
	ar1 = ['1', '2', '3']
	ar1 = set(ar1)
	if set(string) != ar1:
		return 0
	(l, m, r) = (-1, -1, -1)
	ansf = len(string)
	for (index, value) in enumerate(string):
		if value == '1':
			l = index
		elif value == '2':
			m = index
		else:
			r = index
		if l > -1 and m > -1 and (r > -1):
			ansf = min(ansf, max(l, m, r) - min(l, m, r) + 1)
	return ansf
t = int(input())
ans = []
for s in range(t):
	strt = input()
	ans.append(solve(strt))
for it in ans:
	print(it)


t = int(input())
for _ in range(t):
	s = str(input())
	r = [0, 0, 0]
	min_distance = 10 ** 9
	for i in range(len(s)):
		r[int(s[i]) - 1] = i + 1
		if r.count(0) == 0:
			min_distance = min(min_distance, max(r) - min(r))
	if min_distance == 10 ** 9:
		print(0)
	else:
		print(min_distance + 1)


import sys
TEST = 0
if TEST == 1:
	input_file = open('inputB.txt', 'r')
	input_from_file = input_file.readlines()

def read_int():
	if TEST:
		return int(input_from_file.pop(0))
	else:
		return int(sys.stdin.readline())

def read_ints():
	if TEST:
		return list(map(int, input_from_file.pop(0).rstrip().split()))
	else:
		return list(map(int, sys.stdin.readline().split()))

def read_str_to_list():
	if TEST:
		in1 = input_from_file.pop(0).rstrip()
	else:
		in1 = sys.stdin.readline()
	return in1
t = read_int()
for test in range(t):
	s = read_str_to_list()
	L = len(s)
	min_length = L + 1
	last1 = -1
	last2 = -1
	last3 = -1
	j = 0
	while j < L:
		if s[j] == '1':
			last1 = j
		elif s[j] == '2':
			last2 = j
		elif s[j] == '3':
			last3 = j
		if last1 != -1 and last2 != -1 and (last3 != -1):
			cur_length = max(last1, last2, last3) - min(last1, last2, last3) + 1
			if cur_length < min_length:
				min_length = cur_length
		if min_length == 3:
			break
		j += 1
	if min_length == L + 1:
		print(0)
	else:
		print(min_length)


for i in range(int(input())):
	line = input()
	if '1' not in line or '2' not in line or '3' not in line:
		print(0)
	elif len(line) == 3:
		print(3)
	else:
		line += '0'
		sign = line[0]
		coun = 0
		s = []
		for elem in line:
			if elem == sign:
				coun += 1
			else:
				s.append((sign, coun))
				sign = elem
				coun = 1
		ans = 10 ** 7
		for j in range(1, len(s) - 1):
			a = [s[j - 1][0], s[j][0], s[j + 1][0]]
			if '1' in a and '2' in a and ('3' in a):
				ans = min(ans, s[j][1] + 2)
		print(ans)


for _ in range(int(input())):
	s = input()
	mini = len(s)
	pee = set()
	m = len(s)
	l = [-1] * 3
	for i in range(mini):
		l[int(s[i]) - 1] = i + 1
		if len(pee) != 3:
			pee.add(s[i])
		if len(pee) == 3:
			m = min(m, max(l) - min(l) + 1)
	if len(pee) != 3:
		m = 0
	print(m)


import os
import sys
from io import BytesIO, IOBase
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))
input = lambda : sys.stdin.readline().rstrip('\r\n')
from math import factorial
from collections import Counter, defaultdict
from heapq import heapify, heappop, heappush

def RL():
	return map(int, sys.stdin.readline().rstrip().split())

def RLL():
	return list(map(int, sys.stdin.readline().rstrip().split()))

def N():
	return int(input())

def comb(n, m):
	return factorial(n) / (factorial(m) * factorial(n - m)) if n >= m else 0

def perm(n, m):
	return factorial(n) // factorial(n - m) if n >= m else 0

def mdis(x1, y1, x2, y2):
	return abs(x1 - x2) + abs(y1 - y2)
mod = 998244353
INF = float('inf')

def main():
	for _ in range(N()):
		s = input()
		(l, r) = (0, 0)
		le = len(s)
		arr = [0, 0, 0]
		dic = {'1': 0, '2': 1, '3': 2}
		res = INF
		while r < le:
			while r < le and 0 in arr:
				arr[dic[s[r]]] += 1
				r += 1
			while 0 not in arr:
				arr[dic[s[l]]] -= 1
				l += 1
				res = min(res, r - l + 1)
		print(res if res != INF else 0)
main()


from collections import deque, Counter

def solve():
	S = list(map(int, list(input().strip())))
	C = Counter(S)
	if C[1] > 0 and C[2] > 0 and (C[3] > 0):
		ans = C[1] + C[2] + C[3]
	else:
		return 0
	nums = [0] * 4
	d = deque()
	for s in S:
		d.append(s)
		nums[s] += 1
		while d:
			if nums[d[0]] > 1:
				nums[d.popleft()] -= 1
			else:
				break
		if nums[1] > 0 and nums[2] > 0 and (nums[3] > 0):
			if sum(nums) < ans:
				ans = sum(nums)
	return ans

def main():
	t = int(input())
	print('\n'.join(map(str, [solve() for _ in range(t)])))
main()


from sys import stdin, stdout
import heapq as hq
from collections import defaultdict
t = int(input())
for tc in range(t):
	s = stdin.readline().strip()
	best = len(s) + 1
	(a, b, c) = (0, 0, 0)
	h = -1
	t = 0
	found = False
	while best > 3:
		if a * b * c == 0 or h - t < 2:
			h += 1
			if h == len(s):
				break
			if s[h] == '1':
				a += 1
			elif s[h] == '2':
				b += 1
			else:
				c += 1
		else:
			found = True
			if h - t + 1 < best:
				best = h - t + 1
			if s[t] == '1':
				a -= 1
			elif s[t] == '2':
				b -= 1
			else:
				c -= 1
			t += 1
	if not found:
		res = 0
	else:
		res = best
	stdout.write(str(res) + '\n')


for _ in ' ' * int(input()):
	a = input()
	z = len(a)
	s = [-1] * 3
	r = 200005
	for i in range(z):
		if a[i] == '1':
			s[0] = i
		elif a[i] == '2':
			s[1] = i
		else:
			s[2] = i
		if min(s) != -1:
			r = min(r, max(s) - min(s) + 1)
	print(r if r != 200005 else 0)


for _ in range(int(input())):
	s = input()
	(a, b, c, ans) = (float('inf'), float('inf'), float('inf'), float('inf'))
	for i in range(len(s)):
		if s[i] == '1':
			a = i
		if s[i] == '2':
			b = i
		if s[i] == '3':
			c = i
		ans = min(ans, max(a, b, c) - min(a, b, c))
	print(0) if ans >= 200000 else print(ans + 1)


for _ in range(int(input())):
	arr = list(map(int, list(input())))
	amounts = [1]
	numbers = [arr[0]]
	ind = 0
	for i in range(1, len(arr)):
		if arr[i] != numbers[ind]:
			amounts.append(1)
			numbers.append(arr[i])
			ind += 1
		else:
			amounts[ind] += 1
	minWas = 999999999999999
	for i in range(len(amounts) - 2):
		if len(set(numbers[i:i + 3])) == 3:
			minWas = min(minWas, 2 + amounts[i + 1])
	print(0 if minWas == 999999999999999 else minWas)


for _ in range(int(input())):
	s = input()
	n = len(s)
	d = {'1': -1, '2': -1, '3': -1}
	ans = n
	for i in range(n):
		d[s[i]] = i
		ps = d.values()
		pos_min = min(ps)
		if pos_min > -1:
			pos_max = max(ps)
			ans = min(ans, pos_max - pos_min + 1)
	if min(d.values()) > -1:
		print(ans)
	else:
		print(0)


import re
for _ in range(int(input())):
	string = ''.join(input().split())
	numbers = [1, 2, 3]
	result = []
	pat = re.compile('1+|2+|3+')
	same = [(a.start(0), a.end(0)) for a in re.finditer(pat, string)]
	if len(same) > 2:
		same.pop(0)
		same.pop(-1)
		for i in same:
			(x, y) = i
			if string[x - 1] != string[y]:
				result.append(y - x + 2)
		result.sort()
	if len(result) == 0:
		print(0)
	else:
		print(result[0])


import bisect
import os
from collections import Counter
import bisect
from collections import defaultdict
import math
import random
import heapq as hq
from math import sqrt
import sys
from functools import reduce, cmp_to_key
from collections import deque
import threading
from itertools import combinations
from io import BytesIO, IOBase
from itertools import accumulate

def primeFactors(n):
	prime = set()
	while n % 2 == 0:
		prime.add(2)
		n = n // 2
	for i in range(3, int(math.sqrt(n)) + 1, 2):
		while n % i == 0:
			prime.add(i)
			n = n // i
	if n > 2:
		prime.add(n)
	return list(prime)

def getFactors(n):
	factors = []
	i = 1
	while i <= math.sqrt(n):
		if n % i == 0:
			if n // i == i:
				factors.append(i)
			else:
				factors.append(i)
				factors.append(n // i)
		i = i + 1
	return factors

def SieveOfEratosthenes(n):
	prime = [True for i in range(n + 1)]
	p = 2
	while p * p <= n:
		if prime[p] == True:
			for i in range(p * p, n + 1, p):
				prime[i] = False
		p += 1
	num = []
	for p in range(2, n + 1):
		if prime[p]:
			num.append(p)
	return num

def lcm(a, b):
	return a * b // math.gcd(a, b)

def sort_dict(key_value):
	return sorted(key_value.items(), key=lambda kv: (kv[1], kv[0]))

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

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

def string_list():
	return list(input())

def decimalToBinary(n):
	return bin(n).replace('0b', '')

def binaryToDecimal(n):
	return int(n, 2)

def solve():
	s = list(input())
	indx = 0
	ans = 0
	count = 10 ** 10
	occur = {'1': 0, '2': 0, '3': 0}
	for i in range(len(s)):
		occur[s[i]] += 1
		if occur[s[i]] == 1:
			ans += 1
		while indx <= i and occur[s[indx]] > 1:
			occur[s[indx]] -= 1
			indx += 1
		if ans == 3:
			if i - indx + 1 < count:
				count = i - indx + 1
	if count == 10 ** 10:
		print(0)
	else:
		print(count)
t = int(input())
for _ in range(t):
	solve()


from sys import stdin
for _ in range(int(stdin.readline())):
	s = input()
	t = [-1] * 3
	res = len(s)
	for (i, value) in enumerate(s):
		t[int(value) - 1] = i
		if min(t) > -1 and max(t) - min(t) + 1 < res:
			res = max(t) - min(t) + 1
	if min(t) == -1:
		res = 0
	print(res)


MOD = 1000000007
mod = 10009
import math

def primeseive(n):
	prime = [True for i in range(n + 1)]
	p = 2
	while p * p <= n:
		if prime[p] == True:
			for i in range(p * p, n + 1, p):
				prime[i] = False
		p += 1
	ans = [i for i in range(2, n + 1) if prime[i]]
	print(ans)

def checkprime(n):
	if n == 2:
		return True
	if n % 2 == 0 or n <= 1:
		return False
	sqr = int(math.sqrt(n)) + 1
	for d in range(3, sqr, 2):
		if n % d == 0:
			return False
	return True

def primeFactors(n):
	prime = set()
	while n % 2 == 0:
		prime.add(2)
		n = n // 2
	for i in range(3, int(math.sqrt(n)) + 1, 2):
		while n % i == 0:
			prime.add(i)
			n = n // i
	if n > 2:
		prime.add(n)
	return list(prime)

def sort_dict(key_value):
	return sorted(key_value.items(), key=lambda kv: (kv[1], kv[0]))

def xymodm(x, y, m):
	res = 1
	x = x % m
	if x == 0:
		return 0
	while y > 0:
		if y & 1:
			res = res * x % m
		y = y // 2
		x = x * x % m
	return res

def gcd(x, y):
	while y:
		(x, y) = (y, x % y)
	return x

def subarray(a):
	sub = [[]]
	for item in sorted(a):
		sub += [prevsub + [item] for prevsub in sub]
	return sorted(sub)

def check(a, b, c, d):
	ans = 0
	cnt = b
	ind = 0.0
	flag = True
	if a <= b:
		ans = b
	elif a > b:
		if c - d < 0:
			ans = -1
		else:
			ind = (a - b) / (c - d)
			ans = math.ceil(ind)
			ans = ans * c + b
	print(ans)

def solve(s):
	k = [0, 0, 0]
	f = [0, 0, 0]
	m = len(s) + 3
	for j in range(0, len(s)):
		d = int(s[j])
		k[d - 1] = 1
		f[d - 1] = j
		if k[0] * k[1] * k[2] == 1:
			ma = max(f) - min(f) + 1
			if ma < m:
				m = ma
	if sum(k) < 3:
		print(0)
	else:
		print(m)
for i in range(int(input())):
	s = input()
	solve(s)


import sys, math, bisect
from collections import Counter, defaultdict as dd

def data():
	return sys.stdin.readline().strip()

def out(var):
	sys.stdout.write(str(var))

def l():
	return list(sp())

def strl():
	return list(strsp())

def sp():
	return map(int, data().split())

def strsp():
	return map(str, data().split())
for _ in range(int(data())):
	a = data()
	if '1' not in a or '2' not in a or '3' not in a:
		print(0)
	else:
		(b, c, d) = (-1, -1, -1)
		e = []
		g = 1000000000000000000
		for i in range(len(a)):
			if a[i] == '1':
				b = i
			if a[i] == '2':
				c = i
			if a[i] == '3':
				d = i
			if b > -1 and c > -1 and (d > -1):
				g = min(g, max(b, c, d) - min(b, c, d) + 1)
		print(g)


import collections

def minWindow(s, t):
	(need, missing) = (collections.Counter(t), len(t))
	i = I = J = 0
	for (j, c) in enumerate(s, 1):
		missing -= need[c] > 0
		need[c] -= 1
		if not missing:
			while i < j and need[s[i]] < 0:
				need[s[i]] += 1
				i += 1
			if not J or j - i <= J - I:
				(I, J) = (i, j)
	return s[I:J]
t = int(input())
for i in range(t):
	s = input()
	print(len(minWindow(s, '123')))


from collections import defaultdict
t = 1
t = int(input())
for tt in range(t):
	a = input()
	d = len(set([x for x in a]))
	c = defaultdict(lambda : 0)
	cc = 0
	t = 0
	s = -1
	m = 10000000000000000
	for j in range(len(a)):
		c[a[j]] += 1
		if c[a[j]] == 1:
			cc += 1
		if cc == d:
			while c[a[t]] > 1:
				if c[a[t]] > 1:
					c[a[t]] -= 1
				t += 1
			l = j - t + 1
			if m > l:
				m = l
				s = t
	if len(set(a)) == 3:
		print(len(a[s:s + m]))
	else:
		print(0)


for t in range(int(input().strip())):
	a = {'1': -1, '2': -1, '3': -1}
	ans = 10 ** 6
	s = input().strip()
	for i in range(len(s)):
		a[s[i]] = i
		ps = a.values()
		pos_min = min(ps)
		if pos_min > -1:
			pos_max = max(ps)
			ans = min(ans, pos_max - pos_min + 1)
	if min(a.values()) == -1:
		ans = 0
	print(ans)


import math
for _ in range(int(input())):
	s = input()
	req = {'1': 1, '2': 1, '3': 1}
	si = 0
	ei = 0
	ct = 3
	mxl = float('inf')
	while ei < len(s):
		req[s[ei]] -= 1
		if req[s[ei]] == 0:
			ct -= 1
		if ct == 0:
			mxl = min(ei - si + 1, mxl)
			while si < ei and ct == 0:
				mxl = min(ei - si + 1, mxl)
				req[s[si]] += 1
				if req[s[si]] > 0:
					ct += 1
					break
				si += 1
			si += 1
		ei += 1
	if mxl == float('inf'):
		print(0)
		continue
	print(mxl)


import math as m
try:
	t = int(input())
	for i in range(t):
		a = input()
		one = -1
		two = -1
		three = -1
		length = []
		mini = len(a) + 1
		for j in range(len(a)):
			aj = int(a[j])
			if aj == 1:
				one = j
			elif aj == 2:
				two = j
			else:
				three = j
			if one > -1 and two > -1 and (three > -1):
				if mini > j - min(one, two, three):
					mini = j - min(one, two, three)
		if mini > len(a):
			print('0')
		else:
			print(mini + 1)
except EOFError:
	exit(0)


from bisect import bisect_left, bisect_right
INF = 1 << 60
t = int(input())
for i in range(t):
	s = input()
	n = len(s)
	start = 0
	x = [[] for i in range(3)]
	for j in range(1, n):
		if s[j] != s[j - 1]:
			x[int(s[j - 1]) - 1].append(start)
			start = j
	x[int(s[-1]) - 1].append(start)
	ans = INF
	for j in range(n - 2):
		if s[j] == s[j + 1]:
			continue
		index = j
		ok = True
		for k in range(3):
			if int(s[j]) - 1 == k:
				continue
			index2 = bisect_right(x[k], j)
			if index2 == len(x[k]):
				ok = False
				break
			index = max(index, x[k][index2])
		if ok:
			ans = min(ans, index - j + 1)
	if ans == INF:
		ans = 0
	print(ans)


from pprint import pprint
import sys
q = int(input())
for _ in range(q):
	have = [0] * 3
	s = input()
	s = list(s)
	s = list(map(lambda x: int(x) - 1, s))
	sl = len(s)
	(l, r) = (0, 0)
	res = 9999999999999999999999
	have[s[0]] = True
	while r <= sl:
		if have[0] == 0 or have[1] == 0 or have[2] == 0:
			r += 1
			if r >= sl:
				break
			have[s[r]] += 1
		else:
			res = min(res, r - l + 1)
			have[s[l]] -= 1
			l += 1
	print(res if res != 9999999999999999999999 else 0)


t = int(input())
for _ in range(t):
	s = list(map(int, list(input())))
	(i, j) = (0, 0)
	ar = [-1, -1, -1]
	ans = len(s) + 465
	for i in range(len(s)):
		ar[s[i] - 1] = i
		if min(ar) != -1:
			ans = min(ans, max(ar) - min(ar) + 1)
	if ans == len(s) + 465:
		print(0)
	else:
		print(ans)


import sys
input = sys.stdin.buffer.readline
t = int(input())
for _ in range(t):
	string = str(input())
	p1 = -1
	p2 = -1
	p3 = -1
	x = 2 * len(string)
	for i in range(len(string)):
		if string[i] == '1':
			p1 = i
		elif string[i] == '2':
			p2 = i
		elif string[i] == '3':
			p3 = i
		if p1 != -1 and p2 != -1 and (p3 != -1):
			x = min(x, max(p1, p2, p3) - min(p1, p2, p3))
	if p1 == -1 or p2 == -1 or p3 == -1:
		print(0)
	else:
		print(x + 1)


n = int(input())
while n > 0:
	n -= 1
	s = input()
	d = [[-1] * 3 for _ in range(len(s))]
	d[0][int(s[0]) - 1] = 0
	for i in range(1, len(s)):
		d[i][0] = d[i - 1][0]
		d[i][1] = d[i - 1][1]
		d[i][2] = d[i - 1][2]
		d[i][int(s[i]) - 1] = i
	min_len = float('inf')
	for i in range(len(d)):
		farthest = min(d[i])
		if farthest == -1:
			continue
		min_len = min(min_len, i - farthest + 1)
	if min_len == float('inf'):
		print(0)
	else:
		print(min_len)


for _ in range(int(input())):
	s = input()
	cnt1 = int(s[0] == '1')
	cnt2 = int(s[0] == '2')
	cnt3 = int(s[0] == '3')
	l = 0
	r = 0
	ans = 0
	while l <= r < len(s):
		if cnt1 >= 1 and cnt2 >= 1 and (cnt3 >= 1):
			if ans == 0:
				ans = r - l + 1
			else:
				ans = min(ans, r - l + 1)
			if s[l] == '1':
				cnt1 -= 1
			elif s[l] == '2':
				cnt2 -= 1
			else:
				cnt3 -= 1
			l += 1
		else:
			if r == len(s) - 1:
				break
			r += 1
			if s[r] == '1':
				cnt1 += 1
			elif s[r] == '2':
				cnt2 += 1
			else:
				cnt3 += 1
	print(ans)


no_of_chars = 4

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


t = int(input())
for i in range(t):
	seq = input()
	seen = set()
	t = [-1, -1, -1]
	t[int(seq[0]) - 1] = 0
	pos = 0
	m = 999999999
	while pos < len(seq):
		t[int(seq[pos]) - 1] = pos
		if -1 not in t:
			ans = max(t) - min(t) + 1
			if ans < m:
				m = ans
		pos += 1
	if m == 999999999:
		print(0)
	else:
		print(m)


for _ in range(int(input())):
	n = list(map(str, input()))
	o = -1
	t = -1
	th = -1
	co = []
	for i in range(len(n)):
		if n[i] == '1':
			o = i
		elif n[i] == '2':
			t = i
		elif n[i] == '3':
			th = i
		l = [o, t, th]
		if -1 not in l:
			co.append(max(l) - min(l) + 1)
	if len(co) == 0:
		print(0)
	else:
		print(min(co))


t = input()
for _ in range(int(t)):
	s = input()
	c1 = c2 = c3 = 0
	n = len(s)
	for i in range(n):
		if s[i] == '1':
			c1 += 1
		elif s[i] == '2':
			c2 += 1
		else:
			c3 += 1
	if c1 == 0 or c2 == 0 or c3 == 0:
		ans = 0
	else:
		a = []
		c = []
		i = 0
		while i < n:
			elem = s[i]
			ct = 1
			j = i + 1
			while j < n:
				if s[j] != elem:
					a.append(elem)
					c.append(ct)
					i = j
					break
				ct += 1
				j += 1
			if j >= n:
				a.append(elem)
				c.append(ct)
				break
		ans = 1000000
		i = 0
		n = len(a)
		while i <= n - 3:
			temp = [a[i], a[i + 1], a[i + 2]]
			if len(set(temp)) == 3:
				ans = min(ans, 2 + c[i + 1])
			i += 1
	print(ans)


import math
t = int(input())
for test in range(t):
	s = input()
	arr = [[int(s[0]), 0]]
	lptr = 0
	for i in range(len(s)):
		if int(s[i]) != arr[lptr][0]:
			arr.append([int(s[i]), i])
			lptr += 1
	ans = 10 ** 9 + 7
	for i in range(2, len(arr)):
		tarr = [arr[i][0], arr[i - 1][0], arr[i - 2][0]]
		tarr.sort()
		if tarr[0] == 1 and tarr[1] == 2 and (tarr[2] == 3):
			ans = min(ans, arr[i][1] - arr[i - 1][1] + 2)
	if ans == 10 ** 9 + 7:
		ans = 0
	print(ans)


def findMinLenStr(str, k):
	n = len(str)
	(st, end) = (0, 0)
	cnt = [0] * 26
	distEle = 0
	currlen = 0
	minlen = n
	startInd = -1
	while end < n:
		cnt[ord(str[end]) - ord('a')] += 1
		if cnt[ord(str[end]) - ord('a')] == 1:
			distEle += 1
		if distEle > k:
			while st < end and distEle > k:
				if cnt[ord(str[st]) - ord('a')] == 1:
					distEle -= 1
				cnt[ord(str[st]) - ord('a')] -= 1
				st += 1
		if distEle == k:
			while st < end and cnt[ord(str[st]) - ord('a')] > 1:
				cnt[ord(str[st]) - ord('a')] -= 1
				st += 1
			currlen = end - st + 1
			if currlen < minlen:
				minlen = currlen
				startInd = st
		end += 1
	return str[startInd:startInd + minlen]
for _ in range(int(input())):
	s = list(input())
	for i in range(len(s)):
		if s[i] == '1':
			s[i] = 'a'
		if s[i] == '2':
			s[i] = 'b'
		if s[i] == '3':
			s[i] = 'c'
	(d, k) = ('', 3)
	for i in s:
		d += i
	y = len(d)
	if s.count('a') > 0 and s.count('b') > 0 and (s.count('c') > 0):
		if y == 3:
			print(3)
		else:
			h = len(findMinLenStr(d, k))
			print(y) if h == 0 else print(h)
	else:
		print(0)


import sys
input = sys.stdin.readline
import heapq
import copy
import math

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

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

def insr():
	s = input()
	return list(s[:len(s) - 1])

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

class Node:

	def _init_(self, val):
		self.data = val
		self.left = None
		self.right = None

def bin_search(arr, l, r, val):
	if arr[r] <= val:
		return r + 1
	if r - l < 2:
		if arr[l] > val:
			return l
		else:
			return r
	mid = int((l + r) / 2)
	if arr[mid] <= val:
		return bin_search(arr, mid, r, val)
	else:
		return bin_search(arr, l, mid, val)

def pr_list(a):
	print(*a, sep=' ')

def find_permut(hashm, l):
	ans = 1
	total = math.factorial(l)
	for i in hashm:
		if i != 0:
			ans = ans * math.factorial(i)
	return int(total / ans)

def main():
	tests = inp()
	mod = 1000000007
	limit = 10 ** 18
	for test in range(tests):
		s = insr()
		dp = [0 for i in range(4)]
		l = 0
		r = 0
		n = len(s)
		length = sys.maxsize
		while True:
			flag = 0
			if r == n:
				break
			while r <= n:
				if dp[1] > 0 and dp[2] > 0 and (dp[3] > 0):
					flag = 1
					break
				elif r == n:
					break
				else:
					dp[int(s[r])] = dp[int(s[r])] + 1
					r = r + 1
			if flag == 1:
				while l < r:
					if dp[1] == 0 or dp[2] == 0 or dp[3] == 0:
						break
					else:
						dp[int(s[l])] = dp[int(s[l])] - 1
						l = l + 1
				length = min(length, r - (l - 1))
			else:
				break
		if length == sys.maxsize:
			print(0)
		else:
			print(length)
main()


from collections import defaultdict
from sys import stdin, stdout

def findSubString(str):
	n = len(str)
	count = 0
	start = 0
	min_len = 10 ** 9
	dist_count = len(set([x for x in str]))
	if dist_count < 3:
		return 0
	curr_count = defaultdict(int)
	for j in range(n):
		curr_count[str[j]] += 1
		if curr_count[str[j]] == 1:
			count += 1
		if count == dist_count:
			while curr_count[str[start]] > 1:
				if curr_count[str[start]] > 1:
					curr_count[str[start]] -= 1
				start += 1
			len_window = j - start + 1
			if min_len > len_window:
				min_len = len_window
	return min_len
for _ in range(int(stdin.readline().strip())):
	n = stdin.readline().strip()
	print(findSubString(n))


nb_cases = int(input())
while nb_cases > 0:
	nb_cases -= 1
	s = input()
	if len(s) < 3:
		print(0)
		continue
	dp1 = [0] * (len(s) + 1)
	dp2 = [0] * (len(s) + 1)
	dp3 = [0] * (len(s) + 1)
	min_sub = 222222
	for x in range(1, len(s) + 1):
		char = int(s[x - 1])
		if char == 1:
			dp1[x] = 1
			if dp2[x - 1] != 0:
				dp2[x] = dp2[x - 1] + 1
			if dp3[x - 1] != 0:
				dp3[x] = dp3[x - 1] + 1
		if char == 2:
			dp2[x] = 1
			if dp1[x - 1] != 0:
				dp1[x] = dp1[x - 1] + 1
			if dp3[x - 1] != 0:
				dp3[x] = dp3[x - 1] + 1
		if char == 3:
			dp3[x] = 1
			if dp1[x - 1] != 0:
				dp1[x] = dp1[x - 1] + 1
			if dp2[x - 1] != 0:
				dp2[x] = dp2[x - 1] + 1
		min_x = max(dp1[x], dp2[x], dp3[x])
		if dp1[x] > 0 and dp2[x] > 0 and (dp3[x] > 0) and (min_x < min_sub):
			min_sub = min_x
	if min_sub == 222222:
		print(0)
	else:
		print(min_sub)


def main():
	t = int(input())
	for __ in range(t):
		s = input()
		index = [-1] * 3
		n = len(s)
		size = 2000000000.0
		for i in range(n):
			index[ord(s[i]) - ord('1')] = i
			if min(index) >= 0:
				size = min(size, max(index) - min(index) + 1)
		if size == 2000000000.0:
			print(0)
		else:
			print(size)
main()


from collections import defaultdict
import sys
import math
sys.setrecursionlimit(1000000)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep='\n')
p2S = lambda x: print(*x, sep='')

def II():
	return int(sys.stdin.readline())

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

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

def LLI(rows_number):
	return [LI() for _ in range(rows_number)]

def SI():
	return sys.stdin.readline()[:-1]

def main():
	for _ in range(II()):
		a = SI()
		k1 = k2 = k3 = False
		f1 = f2 = f3 = 0
		ans = 999999999
		for s in range(len(a)):
			if a[s] == '1':
				f1 = s
				k1 = True
			elif a[s] == '2':
				f2 = s
				k2 = True
			elif a[s] == '3':
				f3 = s
				k3 = True
			if k1 == True and k2 == True and (k3 == True):
				ans = min(ans, max(f1, f2, f3) - min(f1, f2, f3))
		if ans == 999999999:
			print(0)
		else:
			print(ans + 1)
main()


def ternary(s):
	if '1' not in s or '2' not in s or '3' not in s:
		return 0
	k = []
	l = [0] * 3
	for j in range(len(s)):
		l[int(s[j]) - 1] = j + 1
		if l[0] * l[1] * l[2]:
			k.append(max(l) - min(l) + 1)
	return min(k)
ternary('12121212')
for _ in [0] * int(input()):
	print(ternary(input()))


t = int(input())
for i in range(t):
	s = input()
	count = 0
	rep = [0] * 4
	start = 0
	mn_len = float('inf')
	n = len(s)
	for i in range(n):
		rep[int(s[i])] += 1
		if rep[int(s[i])] == 1:
			count += 1
		if count == 3:
			while rep[int(s[start])] > 1:
				if rep[int(s[start])] > 1:
					rep[int(s[start])] -= 1
				start += 1
			window_len = i - start + 1
			mn_len = min(mn_len, window_len)
	if mn_len == float('inf'):
		print(0)
	else:
		print(mn_len)


from itertools import *
for s in [*open(0)][1:]:
	a = [(k, len([*g])) for (k, g) in groupby(s[:-1])]
	print(min([y[1] + 2 for (x, y, z) in zip(a, a[1:], a[2:]) if x[0] != z[0]] or [0]))


test = int(input())
for _ in range(test):
	s = input()
	l = len(s)
	a = b = c = -1
	ans = 999999
	for i in range(l):
		if s[i] == '1':
			a = i
		elif s[i] == '2':
			b = i
		elif s[i] == '3':
			c = i
		if a >= 0 and b >= 0 and (c >= 0):
			x = max(a, b, c)
			y = min(a, b, c)
			z = x - y + 1
			ans = min(ans, z)
	if ans == 999999:
		print(0)
	else:
		print(ans)


t = int(input())
for q in range(t):
	s = list(input())
	ans = float('INF')
	a = 0
	b = 0
	c = 0
	now = 0
	for i in range(len(s)):
		while now < len(s) and a * b * c == 0:
			if s[now] == '1':
				a += 1
			elif s[now] == '2':
				b += 1
			else:
				c += 1
			now += 1
		if a * b * c != 0:
			ans = min(ans, now - i)
		if s[i] == '1':
			a -= 1
		elif s[i] == '2':
			b -= 1
		else:
			c -= 1
	if ans == float('INF'):
		print(0)
	else:
		print(ans)


for _ in range(int(input())):
	s = input()
	m = float('inf')
	items = [-1] * 3
	n = len(s)
	for i in range(n):
		items[int(s[i]) - 1] = i
		if -1 not in items:
			m = min(m, max(items) - min(items) + 1)
	m = 0 if m == float('inf') else m
	print(m)


T = int(input())
for t in range(T):
	s = input()
	if not '1' in s or not '2' in s or (not '3' in s):
		print(0)
		continue
	arr = []
	tp = []
	for i in range(len(s)):
		if i == 0 or s[i] != s[i - 1]:
			arr.append(1)
			tp.append(s[i])
		else:
			arr[-1] += 1
	result = len(s)
	for i in range(len(arr) - 2):
		subt = tp[i:i + 3]
		if '1' in subt and '2' in subt and ('3' in subt):
			result = min(result, arr[i + 1] + 2)
	print(result)


for _ in range(int(input())):
	a = list(input())
	for i in range(len(a)):
		a[i] = int(a[i])
	c = list()
	i = 0
	m = 0
	while m < len(a):
		i = m
		x = a[i]
		while i < len(a) and a[i] == x:
			i = i + 1
		j = i
		if j < len(a):
			y = a[j]
		while j < len(a) and a[j] == y:
			j = j + 1
		if j < len(a) and a[j] != x and (a[j] != y):
			c.append(j - i + 2)
		if j >= len(a):
			break
		m = j - 1
	if len(c) != 0:
		print(min(c))
	else:
		print(0)


for i in range(int(input())):
	S = input()
	l = 0
	r = 0
	ans = 10 ** 10
	A = [0, 0, 0, 0]
	if '1' in S and '2' in S and ('3' in S):
		while r < len(S):
			while A[1] * A[2] * A[3] == 0 and r < len(S):
				A[int(S[r])] += 1
				r += 1
			while A[1] * A[2] * A[3] != 0:
				if ans > sum(A):
					ans = sum(A)
				A[int(S[l])] -= 1
				l += 1
		print(ans)
	else:
		print(0)


from sys import stdin
from bisect import bisect_left

def inp():
	return stdin.readline().strip()

def binary(a, x):
	retVal = bisect_left(a, x)
	if retVal:
		if retVal > len(a):
			return min(a[retVal + 1], a[retVal])
		return a[retVal - 1]
	else:
		return a[0]
t = int(inp())
for _ in range(t):
	s = inp()
	ones = []
	twos = []
	threes = []
	for i in range(len(s)):
		if s[i] == '1':
			ones.append(i)
		elif s[i] == '2':
			twos.append(i)
		elif s[i] == '3':
			threes.append(i)
			answer = 200001
	if ones and twos and threes:
		for i in ones:
			x = binary(twos, i)
			y = binary(threes, i)
			answer = min(answer, max(i, x, y) - min(i, x, y) + 1)
		for i in twos:
			x = binary(ones, i)
			y = binary(threes, i)
			answer = min(answer, max(i, x, y) - min(i, x, y) + 1)
		for i in threes:
			x = binary(ones, i)
			y = binary(twos, i)
			answer = min(answer, max(i, x, y) - min(i, x, y) + 1)
		print(answer)
	else:
		print(0)


def main():
	string = str(input())
	a = list(string)
	s = set(a)
	if len(s) < 3:
		print(0)
		return
	mx = len(a) + 100
	start = 0
	for i in range(len(string) - 1):
		if a[i] != a[i + 1]:
			if a[i + 1] == a[start] or a[i] == a[start]:
				start = i
			elif a[i] != a[start]:
				j = i + 1
				if mx > j - start + 1:
					mx = j - start + 1
					if mx == 3:
						print(3)
						return
				start = i
	print(mx)
t = int(input())
while t:
	main()
	t -= 1


for _ in range(int(input())):
	const = ['1', '2', '3']
	s = input()
	m = 2 * 10 ** 6
	first = second = third = 0
	for i in range(len(s)):
		if i == 0:
			first = 0
			const.remove(s[i])
		elif s[i] == s[i - 1]:
			if len(const) == 2:
				first += 1
			elif len(const) == 1:
				second += 1
		elif len(const) == 2:
			second = i
			const.remove(s[i])
		elif len(const) == 1:
			if s[i] in const:
				third = i
				const.remove(s[i])
				if m > third - first + 1:
					m = third - first + 1
					if m == 3:
						break
				const.append(s[first])
				first = second
				second = third
			else:
				first = second
				second = i
	if third == 0:
		m = 0
	print(m)
	first = second = third = 0


import math
t = int(input())
for i in range(t):
	s = str(input())
	i = 0
	j = 0
	m = {1: 0, 2: 0, 3: 0}
	ans = math.inf
	while j < len(s):
		if m[1] * m[2] * m[3] == 0:
			m[int(s[j])] += 1
			j += 1
		elif m[1] * m[2] * m[3] != 0:
			ans = min(ans, j - i)
			m[int(s[i])] -= 1
			i += 1
	while m[1] * m[2] * m[3] != 0:
		ans = min(ans, j - i)
		m[int(s[i])] -= 1
		i += 1
	if ans == math.inf:
		print(0)
	else:
		print(ans)


for i in range(int(input())):
	A = [0, 0, 0]
	S = input()
	Best = len(S)
	Check = False
	k = 0
	A[int(S[-1]) - 1] += 1
	while k < len(S) - 1:
		A[int(S[k]) - 1] += 1
		if Check:
			last += 1
		if S[k] != S[k + 1]:
			if not Check:
				Check = True
				last = 2
				tmp = str(6 - int(S[k]) - int(S[k + 1]))
			else:
				Check = False
				if S[k + 1] == tmp:
					Best = min(last, Best)
				k -= 1
		k += 1
	if A.count(0):
		print(0)
	else:
		print(Best)


def hhhh(s):
	Max = 30000012321
	n = len(s)
	q = [30243565432124560003, 300034565432456543203, 30345678654340003]
	for i in range(n):
		z = ord(s[i]) - ord('1')
		q[z] = i
		Max = min(Max, max(abs(q[0] - q[1]), abs(q[1] - q[2]), abs(q[0] - q[2])))
	if Max < 1000002:
		return Max
	return -1
for _ in range(int(input())):
	print(hhhh(input()) + 1)


t = int(input())
for _ in range(t):
	s = input()
	n = len(s)
	p = list(s)
	if len(set(p)) == 3:
		d = {'1': 0, '2': 0, '3': 0}
		start = 0
		min1 = len(s)
		c = 0
		l = []
		start = 0
		for i in range(len(s)):
			if d[s[i]] == 0:
				c += 1
			d[s[i]] += 1
			if c == 3:
				while d[s[start]] > 1:
					d[s[start]] -= 1
					start += 1
				min1 = min(min1, i - start + 1)
				d[s[start]] -= 1
				c -= 1
				start += 1
		print(min1)
	else:
		print(0)


def solve(s):
	left = 0
	right = 0
	num = [0] * 4
	minlen = 0
	for i in range(len(s)):
		right = i
		num[int(s[i])] += 1
		while num[1] > 0 and num[2] > 0 and (num[3] > 0):
			if num[int(s[left])] > 1:
				num[int(s[left])] -= 1
				left += 1
			else:
				if minlen > right - left or minlen == 0:
					minlen = right - left + 1
				break
	return minlen
n = int(input())
for _ in range(n):
	print(solve(input()))


t = int(input())
for _ in range(t):
	s = input()
	cur_ind = [-1, -1, -1]
	cur_l = 0
	for (i, (c1, c2)) in enumerate(zip(s[:-1], s[1:])):
		if c2 == c1:
			cur_ind[int(c2) - 1] = i + 1
		else:
			cur_ind[int(c1) - 1] = i
			cur_ind[int(c2) - 1] = i + 1
		if -1 not in cur_ind:
			if cur_l == 0:
				cur_l = max(cur_ind) - min(cur_ind)
			else:
				cur_l = min(cur_l, max(cur_ind) - min(cur_ind))
	if cur_l != 0:
		print(cur_l + 1)
	else:
		print(cur_l)


def minWindow(S):
	T = '123'
	indices = {}
	for char in T:
		indices[char] = []
	miss = list(T)
	start = 0
	end = len(S)
	for i in range(len(S)):
		if S[i] in T:
			if S[i] not in miss and indices[S[i]] != []:
				indices[S[i]].pop(0)
			elif S[i] in miss:
				miss.remove(S[i])
			indices[S[i]].append(i)
		if miss == []:
			maximum = max([x[-1] for x in indices.values()])
			minimum = min([x[0] for x in indices.values()])
			if maximum - minimum + 1 < end - start + 1:
				start = minimum
				end = maximum
	if miss != []:
		return 0
	else:
		return len(S[start:end + 1])
t = int(input())
for i in range(t):
	s = input()
	print(minWindow(s))


t = int(input())
while t > 0:
	_input = input()
	_hash = dict()
	ptr1 = ptr2 = 0
	_min_len = float('inf')
	while ptr1 < len(_input):
		_hash[_input[ptr1]] = _hash.get(_input[ptr1], 0) + 1
		while len(_hash) == 3:
			_min_len = min(_min_len, ptr1 - ptr2 + 1)
			_hash[_input[ptr2]] -= 1
			if _hash[_input[ptr2]] == 0:
				del _hash[_input[ptr2]]
			ptr2 += 1
		ptr1 += 1
	if _min_len == float('inf'):
		print(0)
	else:
		print(_min_len)
	t -= 1


for jokpok in range(int(input())):
	s = input()
	l = [None, None, None]
	ans = None
	for j in range(len(s)):
		l[int(s[j]) - 1] = j
		if l[0] != None and l[1] != None and (l[2] != None):
			m = max(l) - min(l) + 1
			if ans == None or m < ans:
				ans = m
	print((ans, 0)[ans == None])


for i in range(int(input())):
	z = input()
	s = [int(i) for i in z]
	arr = [-1] * 4
	v = []
	for i in range(len(s)):
		arr[s[i]] = i
		if arr[1] >= 0 and arr[2] >= 0 and (arr[3] >= 0):
			v.append(max(arr[1], arr[2], arr[3]) - min(arr[1], arr[2], arr[3]) + 1)
	if v == []:
		print('0')
	else:
		print(min(v))


T = int(input())
for _ in range(0, T):
	s = input()
	c1 = 0
	c2 = 0
	c3 = 0
	i = 0
	ans = len(s) + 100
	for ptr2 in range(0, len(s)):
		if s[ptr2] == '1':
			c1 += 1
		elif s[ptr2] == '2':
			c2 += 1
		elif s[ptr2] == '3':
			c3 += 1
		if c1 * c2 * c3 != 0:
			while c1 * c2 * c3 != 0 and i <= ptr2:
				if s[i] == '1':
					c1 -= 1
				elif s[i] == '2':
					c2 -= 1
				elif s[i] == '3':
					c3 -= 1
				i += 1
				ans = min(ans, ptr2 - i + 2)
	if ans == len(s) + 100:
		print(0)
	else:
		print(ans)


t = int(input())
for T in range(t):
	s = input()
	(one, two, three) = (-10000000000, -10000000000, -10000000000)
	mins = 10000000000
	for i in range(len(s)):
		if s[i] == '1':
			one = i
		if s[i] == '2':
			two = i
		if s[i] == '3':
			three = i
		if one < two and two < three:
			mins = min(mins, three - one + 1)
		elif one < three and three < two:
			mins = min(mins, two - one + 1)
		elif two < one and one < three:
			mins = min(mins, three - two + 1)
		elif two < three and three < one:
			mins = min(mins, one - two + 1)
		elif three < one and one < two:
			mins = min(mins, two - three + 1)
		elif three < two and two < one:
			mins = min(mins, one - three + 1)
	if mins <= len(s):
		print(mins)
	else:
		print(0)


for _ in range(int(input())):
	s = input()
	l = [s[0]]
	f = [1]
	for i in range(1, len(s)):
		if s[i] == s[i - 1]:
			f[-1] += 1
		else:
			l.append(s[i])
			f.append(1)
	ans = len(s) + 1
	for i in range(len(l) - 2):
		p = [l[i], l[i + 1], l[i + 2]]
		if '1' in p and '2' in p and ('3' in p):
			if f[i + 1] + 2 < ans:
				ans = f[i + 1] + 2
	if ans == len(s) + 1:
		print(0)
	else:
		print(ans)


t = int(input())
for ti in range(t):
	s = input()
	n = len(s)
	ans = 100000000
	latest = {'1': None, '2': None, '3': None}
	for (ind, c) in enumerate(s):
		latest[c] = ind
		if latest['1'] is not None and latest['2'] is not None and (latest['3'] is not None):
			thelen = max([abs(latest['1'] - latest['2']), abs(latest['1'] - latest['3']), abs(latest['3'] - latest['2'])]) + 1
			if thelen < ans:
				ans = thelen
	if ans == 100000000:
		ans = 0
	print(ans)


import math
t = int(input())
for i in range(t):
	s = input()
	d = dict()
	r = 1000000000
	p = 0
	for j in range(len(s)):
		d[s[j]] = j
		if '1' in d.keys() and '2' in d.keys() and ('3' in d.keys()):
			q = min(d['1'], d['2'], d['3'])
			y = max(d['1'], d['2'], d['3'])
			r = min(r, y - q + 1)
			p = 1
	if p == 0:
		print(0)
	else:
		print(r)


n = int(input())
for _ in range(n):
	ans = float('inf')
	v = []
	a = input()
	for i in a:
		if v == []:
			v.append(i)
		elif 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)
		elif i != v[0]:
			v.append(i)
	if ans == float('inf'):
		ans = 0
	print(ans)


import sys
input = sys.stdin.readline
for _ in range(int(input())):
	s = input()
	try:
		i = s.index('1')
		j = s.index('2')
		k = s.index('3')
	except:
		print(0)
		continue
	mini = max(i, j, k) - min(i, j, k) + 1
	for (idx, ele) in enumerate(s[:-1]):
		if ele == '1':
			i = idx
		elif ele == '2':
			j = idx
		elif ele == '3':
			k = idx
		mini = min(max(i, j, k) - min(i, j, k) + 1, mini)
	print(mini)


def fun(l):
	mins = 10000000
	a = 0
	b = 0
	s = 0
	d = {}
	d[1] = 0
	d[2] = 0
	d[3] = 0
	while a < len(l) and b < len(l) and (b >= 0):
		d[l[a]] += 1
		if d[1] > 0 and d[2] > 0 and (d[3] > 0) and (a < len(l) and b < len(l)) and (b >= 0):
			s = a - b
			mins = min(mins, s)
			while d[1] > 0 and d[2] > 0 and (d[3] > 0) and (a < len(l) and b < len(l)) and (b >= 0):
				s = a - b
				mins = min(mins, s)
				b += 1
				d[l[b - 1]] -= 1
		a += 1
	if mins == 10000000:
		return 0
	else:
		return mins + 1
t = int(input())
for _ in range(t):
	l = [int(x) for x in input()]
	ans = fun(l)
	print(ans)


import sys, random
from bisect import bisect_left, bisect_right
input = sys.stdin.readline

def main():
	inf = 10 ** 20
	t = int(input())
	for _ in range(1, t + 1):
		pos = [[], [], []]
		s = input().strip()
		for i in range(len(s)):
			pos[int(s[i]) - 1].append(i)
		if len(pos[0]) == 0 or len(pos[1]) == 0 or len(pos[2]) == 0:
			print(0)
			continue
		ans = inf
		for i in range(3):
			for x in pos[0]:
				a = bisect_right(pos[1], x)
				b = bisect_right(pos[2], x)
				if a != len(pos[1]) and b != len(pos[2]):
					total = max(pos[1][a], pos[2][b]) - x
					ans = min(ans, total + 1)
			pos = [pos[1], pos[2], pos[0]]
		print(ans)
main()


import sys
for _ in range(int(input())):
	s = list(input())
	l = len(s)
	x = 0
	y = 0
	z = 0
	f = 0
	m = sys.maxsize
	for i in range(l):
		if s[i] == '1':
			x = i + 1
		elif s[i] == '2':
			y = i + 1
		elif s[i] == '3':
			z = i + 1
		if x > 0 and y > 0 and (z > 0):
			(p, q) = (max(x, max(y, z)), min(x, min(y, z)))
			m = min(m, p - q + 1)
			f = 1
	if f == 0:
		print(0)
	else:
		print(m)


from math import ceil
for tc in range(int(input())):
	s = input()
	l = 200005
	(start, end) = (0, 0)
	mp = {'1': -1, '2': -1, '3': -1}
	for i in range(len(s)):
		mp[s[i]] = i
		(mx, mn) = (max(mp.values()), min(mp.values()))
		if mn != -1:
			l = min(mx - mn + 1, l)
	if l == 200005:
		print(0)
		continue
	print(l)


from sys import stdin
t = int(input())
while t > 0:
	n = input()
	mini = len(n)
	l = list(n)
	s = {1, 2, 3}
	s1 = set()
	i1 = 0
	j1 = 0
	k1 = 0
	count = 0
	for i in range(len(l)):
		s1.add(l[i])
		if l[i] == '1':
			i1 = i
		if l[i] == '2':
			j1 = i
		if l[i] == '3':
			k1 = i
		if len(s1) == 3:
			if i1 <= j1 and i1 <= k1:
				minimum = i1
			elif j1 <= i1 and j1 <= k1:
				minimum = j1
			else:
				minimum = k1
			count = 0
			if i1 >= j1 and i1 >= k1:
				maximum = i1
			elif j1 >= i1 and j1 >= k1:
				maximum = j1
			else:
				maximum = k1
			count = maximum - minimum + 1
			if count <= mini:
				mini = count
	if len(s1) < 3:
		print(0)
	else:
		print(mini)
	t -= 1


no_of_chars = 256

def findSubString(string, pat):
	len1 = len(string)
	len2 = len(pat)
	if len1 < len2:
		return '0'
	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]
T = int(input())
for _ in range(T):
	s = input()
	A = ['123']
	mv = len(s) + 1
	for i in A:
		mv = min(mv, len(findSubString(s, i)))
	if mv >= 3:
		print(mv)
	else:
		print(0)


for _ in range(int(input())):
	s = input()
	m = {'1': 0, '2': 0, '3': 0}
	ans = 2000000000.0
	j = 0
	for i in range(len(s)):
		m[s[i]] += 1
		while m[s[j]] > 1:
			m[s[j]] -= 1
			j += 1
		if m['1'] > 0 and m['2'] > 0 and (m['3'] > 0):
			ans = min(ans, i - j + 1)
	if ans == 2000000000.0:
		ans = 0
	print(ans)


from sys import stdin

def check():
	for i in range(1, 4):
		if c[i] == 0:
			return False
	return True
for t in range(int(input())):
	s = stdin.readline().strip()
	c = [0, 0, 0, 0]
	lt = 0
	if len(s) < 3:
		print(0)
	else:
		for i in range(3):
			c[int(s[i])] += 1
		if check():
			print(3)
		else:
			i = 0
			j = 2
			l = 99999999999999
			while j < len(s):
				if check() == False:
					if j == len(s) - 1:
						break
					j += 1
					c[int(s[j])] += 1
				else:
					while 1:
						if check():
							if l > j - i + 1:
								l = j - i + 1
							c[int(s[i])] -= 1
							i += 1
						else:
							break
			if l == 99999999999999:
				print(0)
			else:
				print(l)


from collections import defaultdict
test = int(input())
while test:
	test -= 1
	s = input()
	l = len(s)
	shortes = 2000000
	(i, j) = (0, 0)
	seen = defaultdict(int)
	while j < l:
		seen[s[j]] += 1
		if seen['1'] >= 1 and seen['2'] >= 1 and (seen['3'] >= 1):
			shortes = min(shortes, j - i + 1)
			while i < j - 1:
				if seen[s[i]] > 1:
					seen[s[i]] -= 1
					i += 1
					shortes = min(shortes, j - i + 1)
				else:
					break
		j += 1
	if seen['1'] == 0 or seen['2'] == 0 or seen['3'] == 0:
		print(0)
		continue
	print(shortes)


n = int(input())
for _ in range(n):
	ans = int(1000000000.0)
	s = input()
	var = [s[0]]
	li = [[s[0], 1]]
	liptr = 0
	for i in range(1, len(s)):
		if s[i] not in var:
			var.append(s[i])
		if s[i] == li[liptr][0]:
			li[liptr][1] += 1
		else:
			li.append([s[i], 1])
			liptr += 1
	if len(var) < 3:
		print(0)
		continue
	for i in range(2, len(li)):
		temp = [li[j][0] for j in range(i - 2, i + 1)]
		temp.sort()
		if temp == ['1', '2', '3']:
			ans = min(ans, 2 + li[i - 1][1])
	print(ans)


from sys import stdin
input = stdin.readline

def main():
	test = int(input())
	for _ in range(test):
		s = input()
		a = -1
		b = -1
		c = -1
		m = len(s) + 1
		for i in range(len(s)):
			if s[i] == '1':
				a = i
			elif s[i] == '2':
				b = i
			elif s[i] == '3':
				c = i
			if a >= 0 and b >= 0 and (c >= 0):
				m = min(m, max(a, b, c) - min(a, b, c) + 1)
		if m == len(s) + 1:
			print(0)
		else:
			print(m)
main()


t = int(input())
from bisect import bisect
for i in range(t):
	s = input()
	l1 = []
	l2 = []
	l3 = []
	for j in range(len(s)):
		if s[j] == '1':
			l1.append(j)
		elif s[j] == '2':
			l2.append(j)
		else:
			l3.append(j)
	ans = len(s) + 1
	for j in range(len(s)):
		if s[j] == '1':
			a = bisect(l2, j)
			b = bisect(l3, j)
			if a != len(l2) and b != len(l3):
				ans = min(ans, max(l2[a], l3[b]) - j + 1)
		elif s[j] == '2':
			a = bisect(l1, j)
			b = bisect(l3, j)
			if a != len(l1) and b != len(l3):
				ans = min(ans, max(l1[a], l3[b]) - j + 1)
		else:
			a = bisect(l1, j)
			b = bisect(l2, j)
			if a != len(l1) and b != len(l2):
				ans = min(ans, max(l1[a], l2[b]) - j + 1)
	if ans != len(s) + 1:
		print(ans)
	else:
		print(0)


for _ in range(int(input())):
	s = input()
	arr = [0] * 4
	l = 0
	dist = len(s) + 1
	n = len(s)
	for r in range(0, len(s)):
		arr[int(s[r])] += 1
		while arr[int(s[l])] > 1:
			arr[int(s[l])] -= 1
			l += 1
		if arr[1] >= 1 and arr[2] >= 1 and (arr[3] >= 1):
			dist = min(dist, r - l + 1)
	if dist == n + 1:
		print(0)
	else:
		print(dist)


for _ in range(int(input())):
	s = input()
	l = [-1] * 4
	i = 0
	m = 200001
	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 < m:
				m = z
		i = i + 1
	if m == 200001:
		print(0)
	else:
		print(m)


t = int(input())
for _ in range(t):
	s = input()
	(a, b, c) = (0, 0, 0)
	r = 0
	ans = 10 ** 9
	for i in range(len(s)):
		while a < 1 or b < 1 or c < 1:
			if r == len(s):
				break
			if s[r] == '1':
				a += 1
			elif s[r] == '2':
				b += 1
			else:
				c += 1
			r += 1
		if a >= 1 and b >= 1 and (c >= 1):
			ans = min(ans, r - i)
		if s[i] == '1':
			a -= 1
		elif s[i] == '2':
			b -= 1
		else:
			c -= 1
	if ans == 10 ** 9:
		print(0)
	else:
		print(ans)


for _ in range(int(input())):
	s = input()
	d = {}
	d['1'] = 0
	d['2'] = 0
	d['3'] = 0
	sumarray = []
	i = 0
	min_size = 200001
	for j in s:
		d[j] += 1
		sumarray.append((d['1'], d['2'], d['3']))
		if min(sumarray[-1]) >= 1:
			while True:
				res = tuple(map(lambda i, j: i - j, sumarray[-1], sumarray[i]))
				if min(res) >= 1:
					i += 1
				else:
					min_size = min(min_size, len(sumarray) - i)
					break
	if min_size == 200001:
		print(0)
		continue
	print(min_size)


def solve(s):
	m = {3: -1000000000.0, 1: -1000000000.0, 2: -1000000000.0}
	ans = 1000000000.0
	for i in range(len(s)):
		m[int(s[i])] = i
		x = min(m.values())
		ans = min(ans, i - x + 1)
	if ans > len(s):
		print(0)
	else:
		print(ans)
for _ in range(int(input())):
	s = input()
	solve(s)


from collections import defaultdict

def find_sub_string(str):
	str_len = len(str)
	dist_count_char = len(set([x for x in str]))
	(ctr, start_pos, start_pos_index, min_len) = (0, 0, -1, 9999999999)
	curr_count = defaultdict(lambda : 0)
	for i in range(str_len):
		curr_count[str[i]] += 1
		if curr_count[str[i]] == 1:
			ctr += 1
		if ctr == dist_count_char:
			while curr_count[str[start_pos]] > 1:
				if curr_count[str[start_pos]] > 1:
					curr_count[str[start_pos]] -= 1
				start_pos += 1
			len_window = i - start_pos + 1
			if min_len > len_window:
				min_len = len_window
				start_pos_index = start_pos
	return str[start_pos_index:start_pos_index + min_len]
t = int(input())
for i in range(t):
	s = input()
	x = len(find_sub_string(s))
	if x < 3:
		print(0)
	else:
		print(x)


from bisect import bisect_left
a = int(input())
import math
for i in range(a):
	one = []
	two = []
	thr = []
	s = input()
	for i in range(len(s)):
		if s[i] == '1':
			one.append(i)
		elif s[i] == '2':
			two.append(i)
		else:
			thr.append(i)
	maxa = math.inf
	for i in range(len(s)):
		if s[i] == '1':
			x = bisect_left(two, i)
			y = bisect_left(thr, i)
			if x == len(two) or y == len(thr):
				continue
			else:
				ind1 = two[x]
				ind2 = thr[y]
				maxa = min(maxa, max(ind1, ind2) - i + 1)
		elif s[i] == '2':
			x = bisect_left(one, i)
			y = bisect_left(thr, i)
			if x == len(one) or y == len(thr):
				continue
			else:
				ind1 = one[x]
				ind2 = thr[y]
				maxa = min(maxa, max(ind1, ind2) - i + 1)
		else:
			x = bisect_left(one, i)
			y = bisect_left(two, i)
			if x == len(one) or y == len(two):
				continue
			else:
				ind1 = one[x]
				ind2 = two[y]
				maxa = min(maxa, max(ind1, ind2) - i + 1)
	if maxa == math.inf:
		print('0')
	else:
		print(maxa)


for _ in range(int(input())):
	S = input()
	List = []
	count = 1
	for i in range(1, len(S)):
		if S[i] == S[i - 1]:
			count += 1
			if i == len(S) - 1:
				List.append((int(S[-1]), count))
		else:
			List.append((int(S[i - 1]), count))
			count = 1
			if i == len(S) - 1:
				List.append((int(S[-1]), 1))
	if len(List) < 3:
		print(0)
		continue
	Min = 10 ** 9
	for i in range(2, len(List)):
		if sorted([List[i][0], List[i - 1][0], List[i - 2][0]]) == [1, 2, 3]:
			Min = min(Min, List[i - 1][1] + 2)
	if Min == 10 ** 9:
		print(0)
	else:
		print(Min)


from math import ceil, floor
t = int(input())
for cnt in range(t):
	s = input()
	c1 = 0
	c2 = 0
	c3 = 0
	res = len(s) + 1
	l = 0
	r = -1
	while r < len(s):
		if c1 > 0 and c2 > 0 and (c3 > 0):
			res = min(res, r - l + 1)
			if s[l] == '1':
				c1 -= 1
			elif s[l] == '2':
				c2 -= 1
			else:
				c3 -= 1
			l += 1
		else:
			r += 1
			if r >= len(s):
				break
			if s[r] == '1':
				c1 += 1
			elif s[r] == '2':
				c2 += 1
			else:
				c3 += 1
	if res > len(s):
		print(0)
	else:
		print(res)


t = int(input())
for i in range(t):
	s = input()
	ind = [-1, -1, -1]
	lens = []
	if len(set(s)) < 3:
		print(0)
		continue
	for (index, elm) in enumerate(s):
		if ind[int(elm) - 1] < index:
			ind[int(elm) - 1] = index
		if ind[0] > -1 and ind[1] > -1 and (ind[2] > -1):
			lens.append(max(abs(ind[0] - ind[1]), abs(ind[0] - ind[2]), abs(ind[2] - ind[1])) + 1)
			if ind[0] < ind[1] and ind[0] < ind[2]:
				ind[0] = -1
			if ind[1] < ind[0] and ind[1] < ind[2]:
				ind[1] = -1
			if ind[2] < ind[1] and ind[2] < ind[0]:
				ind[2] = -1
	print(min(lens))


t = int(input())
for i in range(t):
	s = input()
	c1 = -1
	c2 = -1
	c3 = -1
	r = len(s)
	flag = 0
	min1 = 9999999
	for i in range(r):
		if s[i] == '1':
			c1 = i
		elif s[i] == '2':
			c2 = i
		elif s[i] == '3':
			c3 = i
		if c1 != -1 and c2 != -1 and (c3 != -1):
			ans = max(c1, c2, c3) - min(c1, c2, c3) + 1
			flag = 1
			if min1 > ans:
				min1 = ans
	if flag == 0:
		print('0')
	else:
		print(min1)


INF_INT = 10000000000000000000000

def solution():
	s = input()
	n = len(s)
	(ls, rf) = (0, -1)
	answer = INF_INT
	for i in range(n):
		if s[i] != s[ls]:
			if rf == -1:
				rf = i
			else:
				if s[i] != s[rf]:
					answer = min(answer, i - ls + 1)
					ls = rf
				rf = i
		elif rf == -1:
			ls = i
		else:
			ls = rf
			rf = i
	if answer == INF_INT:
		answer = 0
	print(answer)
t = int(input())
for _ in range(t):
	solution()


def ternaryString(s):
	n = len(s)
	count = 0
	cur = None
	l = []
	for i in range(n):
		if s[i] == cur:
			count += 1
		else:
			if cur != None:
				l.append((cur, count))
			cur = s[i]
			count = 1
	l.append((cur, count))
	flag = 1
	ans = 1000000000000
	for i in range(1, len(l) - 1):
		if l[i - 1][0] != l[i + 1][0]:
			flag = 0
			ans = min(ans, l[i][1] + 2)
	if flag:
		return 0
	else:
		return ans
ans = []
n = int(input())
for i in range(n):
	s = input()
	ans.append(ternaryString(s))
for i in ans:
	print(i)


import math
from sys import stdin, stdout

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

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

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

def I():
	return stdin.readline()

def main():
	for i in range(int(I())):
		s = str(I())
		n1 = -1
		n2 = -1
		n3 = -1
		m = len(s)
		for i in range(m):
			if s[i] == '1':
				n1 = i
			elif s[i] == '2':
				n2 = i
			elif s[i] == '3':
				n3 = i
			if n1 != -1 and n2 != -1 and (n3 != -1):
				m = min(m, max(n1, n2, n3) - min(n1, n2, n3) + 1)
		print(m if n1 != -1 and n2 != -1 and (n3 != -1) else 0)
main()


from collections import defaultdict

def chck(s1, s2):
	if s1 in s2 + s2:
		return 1

def smallest(d, s1, s2):
	val = chck(s1, s2)
	if val == 1:
		return 3
	ng = [0]

	def inc(c):
		d[c] += 1
		if d[c] == 0:
			ng[0] -= 1

	def dec(c):
		if d[c] == 0:
			ng[0] += 1
		d[c] -= 1
	for i in s2:
		dec(i)
	ans = len(s1) + 1
	j = 0
	for i in range(len(s1)):
		while ng[0] > 0:
			if j >= len(s1):
				return ans
			inc(s1[j])
			j += 1
		ans = min(ans, j - i)
		dec(s1[i])
	return ans
t = int(input())
for T in range(t):
	s = input()
	if s.count('1') == 0 or s.count('2') == 0 or s.count('3') == 0:
		print(0)
		continue
	d = defaultdict(int)
	print(smallest(d, s, '123'))


from collections import defaultdict

def findSubString(str):
	n = len(str)
	dist_count = 3
	curr_count = defaultdict(lambda : 0)
	start = 0
	min_len = 300000000
	start_index = -1
	count = 0
	for j in range(n):
		curr_count[str[j]] += 1
		if curr_count[str[j]] == 1:
			count += 1
		if count == dist_count:
			while curr_count[str[start]] > 1:
				if curr_count[str[start]] > 1:
					curr_count[str[start]] -= 1
				start += 1
			len_window = j - start + 1
			if min_len > len_window:
				min_len = len_window
				start_index = start
	if min_len == 300000000:
		return 0
	else:
		return min_len
for _ in range(int(input())):
	s = input()
	print(findSubString(s))


import sys
input = sys.stdin.readline

def main():
	test = int(input())
	for _ in range(test):
		string = input()
		length = len(string) - 1
		one = 3 * length
		two = one
		three = one
		ans = one
		for idx in range(0, length):
			char = string[idx]
			if char == '1':
				one = idx
			elif char == '2':
				two = idx
			else:
				three = idx
			l = min(one, min(two, three))
			r = max(one, max(two, three))
			ans = min(ans, r - l + 1)
			idx += 1
		if ans > length:
			ans = 0
		print(ans)
main()


import collections as cc
import sys
I = lambda : list(map(int, input().split()))
for tc in range(int(input())):
	f = cc.defaultdict(list)
	s = input()
	if len(set(s)) < 3:
		print(0)
	else:
		mi = 10 ** 9 + 7
		(x, y, z) = [0] * 3
		for i in range(len(s)):
			if s[i] == '1':
				x = i + 1
			elif s[i] == '2':
				y = i + 1
			elif s[i] == '3':
				z = i + 1
			if x > 0 and y > 0 and (z > 0):
				c = [x, y, z]
				mi = min(mi, max(c) - min(c) + 1)
		print(mi if mi != 10 ** 9 + 7 else 0)


import collections

def solve(s):
	n = len(s)
	window = collections.deque([])
	count = [0, 0, 0]
	i = 0
	ans = float('inf')
	while i < n:
		ch = s[i]
		window.append(ch)
		count[int(ch) - 1] += 1
		while all([c > 0 for c in count]):
			ans = min(ans, len(window))
			popped = int(window.popleft())
			count[popped - 1] -= 1
		i += 1
	return 0 if ans == float('inf') else ans
t = int(input().strip())
for i in range(t):
	string = input().strip()
	print(solve(string))


t = int(input())
for _ in range(t):
	i1 = -1
	i2 = -1
	i3 = -1
	s = input()
	mi = 0
	for i in range(len(s)):
		if s[i] == '1':
			i1 = i
		if s[i] == '2':
			i2 = i
		if s[i] == '3':
			i3 = i
		if (i1 != -1 and i2 != -1 and (i3 != -1)) and (mi == 0 or mi > max(i1, i2, i3) - min(i1, i2, i3) + 1):
			mi = max(i1, i2, i3) - min(i1, i2, i3) + 1
	print(mi)


def solve(s):
	index1 = -1
	index2 = -1
	index3 = -1
	best_length = 300000
	for i in range(len(s)):
		e = s[i]
		if e == '1':
			index1 = i
		elif e == '2':
			index2 = i
		else:
			index3 = i
		if not (index1 == -1 or index2 == -1 or index3 == -1):
			length = max(index1, index2, index3) - min(index1, index2, index3) + 1
			if length < best_length:
				best_length = length
	if best_length == 300000:
		return 0
	return best_length
n = int(input())
for i in range(n):
	print(solve(input()))


for _ in range(int(input())):
	flag_1 = False
	flag_2 = False
	flag_3 = False
	ans = 200000
	flag_ans = False
	loc_1 = -1
	loc_2 = -1
	loc_3 = -1
	s = input()
	for i in range(len(s)):
		if s[i] == '1':
			flag_1 = True
			loc_1 = i
		if s[i] == '2':
			flag_2 = True
			loc_2 = i
		if s[i] == '3':
			flag_3 = True
			loc_3 = i
		if flag_1 and flag_2 and flag_3:
			flag_ans = True
			ans = min(ans, max(loc_3, loc_2, loc_1) - min(loc_3, loc_2, loc_1))
			if loc_1 == min(loc_3, loc_2, loc_1):
				flag_1 = False
			if loc_2 == min(loc_3, loc_2, loc_1):
				flag_2 = False
			if loc_3 == min(loc_3, loc_2, loc_1):
				flag_3 = False
	if flag_ans:
		print(ans + 1)
	else:
		print(0)


t = int(input())
for _ in range(t):
	s = [int(c) for c in input()]
	currlength = 0
	minlength = len(s)
	start = 0
	end = 3
	count = {1: 0, 2: 0, 3: 0}
	if len(s) < 3:
		print(0)
	else:
		count[s[0]] += 1
		count[s[1]] += 1
		for i in range(2, len(s)):
			end = i
			count[s[i]] += 1
			while count[s[start]] > 1:
				count[s[start]] -= 1
				start += 1
			if count[1] >= 1 and count[2] >= 1 and (count[3] >= 1):
				if minlength > end - start + 1:
					minlength = end - start + 1
		if count[1] >= 1 and count[2] >= 1 and (count[3] >= 1):
			print(minlength)
		else:
			print(0)


for _ in range(int(input())):
	s = input()
	(o, t, f) = (-1, -1, -1)
	ans = 100000000000.0
	for (index, item) in enumerate(s):
		if item == '1':
			o = index
		elif item == '2':
			t = index
		else:
			f = index
		if o > -1 and t > -1 and (f > -1):
			ans = min(ans, max(o, t, f) - min(o, t, f) + 1)
	print(ans if ans != 100000000000.0 else 0)


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)


t = int(input())
from math import *
for x in range(t):
	tq = input()
	lr = 10 ** 7
	mina = -1
	minb = -1
	minc = -1
	for i in range(len(tq)):
		if tq[i] == '1':
			if lr > i - min(minb, minc) and minb != -1 and (minc != -1):
				lr = i - min(minb, minc)
			mina = i
		elif tq[i] == '2':
			if lr > i - min(mina, minc) and mina != -1 and (minc != -1):
				lr = i - min(mina, minc)
			minb = i
		elif tq[i] == '3':
			if lr > i - min(minb, mina) and minb != -1 and (mina != -1):
				lr = i - min(minb, mina)
			minc = i
	if lr != 10 ** 7:
		print(lr + 1)
	else:
		print(0)


testcases = int(input())
for i in range(testcases):
	nums = str(input())
	(i, j, k) = (None, None, None)
	leng1 = []
	flag = False
	for iterator1 in range(len(nums)):
		if nums[iterator1] == '1':
			i = iterator1
		elif nums[iterator1] == '2':
			j = iterator1
		else:
			k = iterator1
		if i is not None and j is not None and (k is not None):
			temp = [abs(i - j), abs(j - k), abs(k - i)]
			string_len = max(temp)
			if string_len == 2:
				print(3)
				flag = True
				break
			else:
				leng1.append(string_len)
	if i is not None and j is not None and (k is not None) and (not flag):
		print(min(leng1) + 1)
	elif not flag:
		print(0)


t = int(input())
for kek in range(t):
	s = input()
	che = [0, 0, 0]
	l = 0
	r = 0
	ans = 10 ** 10
	flag1 = True
	while flag1:
		if min(che) >= 1:
			if che[int(s[l]) - 1] > 1:
				che[int(s[l]) - 1] -= 1
				l += 1
				ans = min(ans, sum(che))
			else:
				ans = min(ans, sum(che))
				if r >= len(s):
					flag1 = False
				else:
					che[int(s[r]) - 1] += 1
					r += 1
		elif r >= len(s):
			flag1 = False
		else:
			che[int(s[r]) - 1] += 1
			r += 1
	if ans == 10 ** 10:
		print(0)
	else:
		print(ans)


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()


t = int(input())
b = []
for k in range(t):
	a = input()
	mini = 10000000000000
	if len(set(a)) < 3:
		mini = 0
	else:
		mass = []
		count = 0
		number = 0
		for i in range(len(a)):
			if i == 0:
				number = a[i]
				mass.append(number)
				count += 1
			elif number == a[i]:
				count += 1
			elif number != a[i]:
				if a[i] not in mass:
					if len(mass) == 1:
						mass.append(a[i])
						number = a[i]
						count = 2
					else:
						mass.append(a[i])
						count += 1
						if len(mass) == 3:
							if count < mini:
								mini = count
							mass = [number, a[i]]
							count = 2
						number = a[i]
				else:
					count = 2
					number = a[i]
	b.append(mini)
for i in b:
	print(i)


import io
import os
from collections import Counter, defaultdict, deque

def solve(S):
	N = len(S)
	best = float('inf')
	i = 0
	j = 0
	freq = Counter()
	while True:
		while j < len(S) and len(freq) < 3:
			freq[S[j]] += 1
			j += 1
		while i < len(S) and len(freq) == 3:
			best = min(best, j - i)
			freq[S[i]] -= 1
			if freq[S[i]] == 0:
				del freq[S[i]]
			i += 1
		if j == len(S):
			break
	if best == float('inf'):
		return 0
	return best
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
T = int(input())
for t in range(T):
	S = input().decode().rstrip()
	ans = solve(S)
	print(ans)


t = int(input())
for _ in range(0, t):
	s = input()
	arr = [0] * 3
	for i in range(0, len(s)):
		temp = ord(s[i])
		arr[temp - 49] += 1
	if arr[0] is 0 or arr[1] is 0 or arr[2] is 0:
		print('0')
	else:
		(best1, best2, best3) = (-1, -1, -1)
		ans = 99999999
		for i in range(0, len(s)):
			if s[i] == '1':
				best1 = i
			if s[i] == '2':
				best2 = i
			if s[i] == '3':
				best3 = i
			if best1 != -1 and best2 != -1 and (best3 != -1):
				p = max(max(best1, best2), best3)
				q = min(min(best1, best2), best3)
				ans = min(ans, p - q + 1)
		print(ans)


from sys import stdin
for _ in range(int(stdin.readline())):
	s = stdin.readline().strip()
	o = t = th = -1
	ans = 10 ** 9
	for i in range(len(s)):
		if s[i] == '1':
			o = i
		elif s[i] == '2':
			t = i
		elif s[i] == '3':
			th = i
		if o != -1 and t != -1 and (th != -1):
			ans = min(ans, max(o, t, th) - min(o, t, th) + 1)
	if ans == 10 ** 9:
		print(0)
	else:
		print(ans)


from sys import stdin, gettrace
if not gettrace():

	def input():
		return next(stdin)[:-1]

def main():

	def solve():
		ss = input()
		last1 = -2 * len(ss)
		last2 = -2 * len(ss)
		last3 = -2 * len(ss)
		shortest = len(ss) + 1
		for (i, s) in enumerate(ss):
			if s == '1':
				last1 = i
			elif s == '2':
				last2 = i
			elif s == '3':
				last3 = i
			if i - min(last1, last2, last3) + 1 < shortest:
				shortest = i - min(last1, last2, last3) + 1
		if shortest > len(ss):
			print(0)
		else:
			print(shortest)
	q = int(input())
	for _ in range(q):
		solve()
main()


t = int(input().strip())
for _ in range(t):
	s = input().strip()
	l = [0] * 3
	k = len(s)
	ans = 0
	init = False
	for i in range(k):
		l[ord(s[i]) - ord('1')] = i + 1
		if 0 not in l:
			res = max(l) - min(l) + 1
			if init == False:
				ans = res
				init = True
			else:
				ans = min(ans, res)
	print(ans)


import sys
try:
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
except:
	pass
for tt in range(int(input())):
	s = input()
	one = two = three = -1
	ans = float('inf')
	for i in range(len(s)):
		if s[i] == '1':
			one = i
		if s[i] == '2':
			two = i
		if s[i] == '3':
			three = i
		if one != -1 and two != -1 and (three != -1):
			ans = min(ans, max(one, two, three) - min(one, two, three) + 1)
	if ans == float('inf'):
		print(0)
	else:
		print(ans)


t = int(input())
for _ in range(0, t):
	s = input()
	dic = dict()
	cc = 0
	start = 0
	ans = 10 ** 9 + 7
	for i in range(0, len(s)):
		if s[i] not in dic:
			dic[s[i]] = 1
		else:
			dic[s[i]] += 1
		if dic[s[i]] == 1:
			cc += 1
		if cc == 3:
			while dic[s[start]] > 1:
				if dic[s[start]] > 1:
					dic[s[start]] -= 1
					start += 1
			ans = min(ans, i - start + 1)
	if ans == 10 ** 9 + 7:
		print(0)
	else:
		print(ans)


from sys import stdin, stdout
from math import gcd, ceil, sqrt
ii1 = lambda : int(stdin.readline().strip())
is1 = lambda : stdin.readline().strip()
iia = lambda : list(map(int, stdin.readline().strip().split()))
isa = lambda : stdin.readline().strip().split()
mod = 1000000007
tc = ii1()
for _ in range(tc):
	arr = [0] * 3
	count = 0
	res = float('inf')
	s = is1()
	cur = set()
	for i in range(len(s)):
		if s[i] not in cur:
			cur.add(s[i])
			count += 1
		arr[int(s[i]) - 1] = i + 1
		if count == 3:
			res = min(res, max(arr) - min(arr) + 1)
			cur.remove(str(arr.index(min(arr)) + 1))
			count -= 1
	if res == float('inf'):
		res = 0
	print(res)


t = int(input())
for _ in range(t):
	s = str(input())
	lens = len(s)
	l = [0, 0, 0]
	mini = float('inf')
	i = 0
	j = -1
	flag = 0
	while True:
		while True:
			if l[0] != 0 and l[1] != 0 and (l[2] != 0):
				mini = min(mini, j - i + 1)
				break
			else:
				j += 1
				if j == lens:
					flag = 1
					break
				l[int(s[j]) - 1] += 1
		if flag == 1:
			break
		l[int(s[i]) - 1] -= 1
		i += 1
	if mini == float('inf'):
		print(0)
	else:
		print(mini)


for _ in range(int(input())):
	(one, two, three) = (-1, -1, -1)
	s = list(input())
	x = False
	ans = len(s)
	for i in range(len(s)):
		if s[i] == '1':
			one = i
		if s[i] == '2':
			two = i
		if s[i] == '3':
			three = i
		if one != -1 and two != -1 and (three != -1):
			x = True
			a = max(one, max(two, three))
			b = min(one, min(two, three))
			ans = min(ans, a - b + 1)
	if x == True:
		print(ans)
	else:
		print(0)


from sys import stdin, stdout
cin = stdin.readline
cout = stdout.write

def binSearch(lst, x):
	m = [10 ** 12] * 2
	high = len(lst) - 1
	low = 0
	dst = 10 ** 12
	while low <= high:
		mid = (low + high) // 2
		if lst[mid] < x:
			if x - lst[mid] < dst:
				m[0] = lst[mid]
				dst = x - lst[mid]
			elif x - lst[mid] == dst:
				m[1] = lst[mid]
			low = mid + 1
		elif lst[mid] > x:
			if lst[mid] - x < dst:
				m[0] = lst[mid]
				dst = lst[mid] - x
			elif lst[mid] - x == dst:
				m[1] = lst[mid]
			high = mid - 1
	return m
for _ in range(int(cin())):
	s = cin()[:-1]
	if '1' not in s or '2' not in s or '3' not in s:
		cout('0\n')
		continue
	(one, two, three) = ([], [], [])
	for i in range(len(s)):
		if s[i] == '1':
			one.append(i)
		elif s[i] == '2':
			two.append(i)
		else:
			three.append(i)
	length = 10 ** 12
	for i in one:
		j = binSearch(two, i)
		k = binSearch(three, i)
		for u in j:
			for v in k:
				y = max(i, u, v) - min(i, u, v) + 1
				length = min(length, y)
	cout(str(length) + '\n')


import sys
input = sys.stdin.readline

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

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

def insr():
	s = input()
	return list(s[:len(s) - 1])

def invr():
	return map(int, input().split())
t = inp()
for _ in range(t):
	x = insr()
	s = set()
	for char in x:
		s.add(char)
	if len(s) < 3:
		print(0)
	else:
		n = len(x)
		hi = n
		lo = 3
		ans = 3
		while hi >= lo:
			mid = (hi + lo) // 2
			ek = 0
			dui = 0
			tin = 0
			for i in range(mid):
				if x[i] == '1':
					ek += 1
				elif x[i] == '2':
					dui += 1
				else:
					tin += 1
			flag = False
			flag |= ek and dui and tin
			for i in range(mid, n):
				if x[i - mid] == '1':
					ek -= 1
				elif x[i - mid] == '2':
					dui -= 1
				else:
					tin -= 1
				if x[i] == '1':
					ek += 1
				elif x[i] == '2':
					dui += 1
				else:
					tin += 1
				flag |= ek and dui and tin
			if flag:
				ans = mid
				hi = mid - 1
			else:
				lo = mid + 1
		print(ans)


import sys
import math
from math import factorial as f
from collections import defaultdict as dd
mod = 1000000007
T = 1
T = int(sys.stdin.readline())
for _ in range(T):
	s = input()
	n = len(s)
	(i1, i2, i3) = (-1, -1, -1)
	ans = len(s) + 5
	for i in range(len(s)):
		if s[i] == '1':
			i1 = i
		elif s[i] == '2':
			i2 = i
		else:
			i3 = i
		if i1 != -1 and i2 != -1 and (i3 != -1):
			l = i - min(i1, min(i2, i3)) + 1
			if l < ans:
				ans = l
	if ans == n + 5:
		print(0)
	else:
		print(ans)


for _ in range(int(input())):
	s = input()
	l = 0
	c = {}
	minL = 9999999
	for i in s:
		c[i] = l
		if len(c) == 3:
			minL = min(minL, int(max(c.values())) - int(min(c.values())) + 1)
		l += 1
	if minL == 9999999:
		print(0)
	else:
		print(minL)


from sys import maxsize

def smallest_subarray(lst, st):
	if len(lst) < len(st):
		return []
	m = {}
	for c in st:
		freq = m.get(c, 0)
		freq += 1
		m[c] = freq
	counter = len(m.keys())
	left = right = 0
	head = 0
	tail = maxsize
	while right < len(lst):
		c = lst[right]
		if c in m:
			freq = m[c]
			freq -= 1
			m[c] = freq
			if freq == 0:
				counter -= 1
		right += 1
		while counter == 0:
			c = lst[left]
			if c in m:
				freq = m[c]
				freq += 1
				m[c] = freq
				if freq > 0:
					counter += 1
			if right - left < tail:
				tail = right - left
				head = left
			left += 1
	if tail == maxsize:
		return []
	return lst[head:head + tail]
t = int(input())
while t:
	ip = input()
	print(len(smallest_subarray(list(ip), ['1', '2', '3'])))
	t -= 1


t = int(input())
for testcase in range(t):
	s = input()
	(fst, scnd, trd) = (0, 0, 0)
	ans = 1000000000.0
	j = 0
	for i in range(len(s)):
		if s[i] == '1':
			fst += 1
		if s[i] == '2':
			scnd += 1
		if s[i] == '3':
			trd += 1
		while fst > 0 and scnd > 0 and (trd > 0) and (j < len(s)):
			if s[j] == '1':
				fst -= 1
			if s[j] == '2':
				scnd -= 1
			if s[j] == '3':
				trd -= 1
			ans = min(ans, i - j + 1)
			j += 1
	if ans == 1000000000.0:
		print(0)
	else:
		print(ans)


def solve():
	s = list(map(int, input()))
	n = len(s)
	if len(s) < 3:
		print(0)
	else:
		last = [-n, -n, -n]
		a = []
		for (index, val) in enumerate(s):
			last[val - 1] = index
			curr = last.copy()
			a.append(curr)
		min_len = n + 1
		for i in a:
			a = min(i)
			b = max(i)
			min_len = min(min_len, b - a + 1)
		if min_len > n:
			print(0)
		else:
			print(min_len)
t = int(input())
for test in range(t):
	solve()


from collections import Counter

def minWindow(s, t):
	if not t or not s:
		return ''
	dict_t = Counter(t)
	required = len(dict_t)
	filtered_s = []
	for (i, char) in enumerate(s):
		if char in dict_t:
			filtered_s.append((i, char))
	(l, r) = (0, 0)
	formed = 0
	window_counts = {}
	ans = (float('inf'), None, None)
	while r < len(filtered_s):
		character = filtered_s[r][1]
		window_counts[character] = window_counts.get(character, 0) + 1
		if window_counts[character] == dict_t[character]:
			formed += 1
		while l <= r and formed == required:
			character = filtered_s[l][1]
			end = filtered_s[r][0]
			start = filtered_s[l][0]
			if end - start + 1 < ans[0]:
				ans = (end - start + 1, start, end)
			window_counts[character] -= 1
			if window_counts[character] < dict_t[character]:
				formed -= 1
			l += 1
		r += 1
	return '' if ans[0] == float('inf') else s[ans[1]:ans[2] + 1]
for _ in range(int(input())):
	s = input()
	t = '123'
	print(len(minWindow(s, t)))


from __future__ import division, print_function
import itertools
import sys
import os
from io import BytesIO, IOBase
if sys.version_info[0] < 3:
	input = raw_input
	range = xrange
	filter = itertools.ifilter
	map = itertools.imap
	zip = itertools.izip

def is_it_local():
	script_dir = str(os.getcwd()).split('/')
	username = 'dipta007'
	return username in script_dir

def READ(fileName):
	if is_it_local():
		sys.stdin = open(f'./{fileName}', 'r')
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')
if not is_it_local():
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
	input = lambda : sys.stdin.readline().rstrip('\r\n')

def input1(type=int):
	return type(input())

def input2(type=int):
	[a, b] = list(map(type, input().split()))
	return (a, b)

def input3(type=int):
	[a, b, c] = list(map(type, input().split()))
	return (a, b, c)

def input_array(type=int):
	return list(map(type, input().split()))

def input_string():
	s = input()
	return list(s)

def main():
	t = input1()
	for ci in range(t):
		s = input_string()
		l = 0
		mp = {'1': 0, '2': 0, '3': 0}
		res = len(s) + 1
		for h in range(len(s)):
			mp[s[h]] += 1
			while mp[s[l]] > 1:
				mp[s[l]] -= 1
				l += 1
			if mp['1'] > 0 and mp['2'] > 0 and (mp['3'] > 0):
				res = min(res, h - l + 1)
		if res > len(s):
			res = 0
		print(res)
	pass
READ('in.txt')
main()


for t in range(int(input())):
	s = input()
	low = 0
	high = 0
	min_len = 200001
	count1 = 0
	count2 = 0
	count3 = 0
	if s[low] == '1':
		count1 = 1
	elif s[low] == '2':
		count2 = 1
	else:
		count3 = 1
	while low <= high:
		if count1 < 1 or count2 < 1 or count3 < 1:
			high += 1
			if high == len(s):
				break
			if s[high] == '1':
				count1 += 1
			elif s[high] == '2':
				count2 += 1
			else:
				count3 += 1
		elif count1 >= 1 and count2 >= 1 and (count3 >= 1):
			min_len = min(min_len, high - low + 1)
			if s[low] == '1':
				count1 -= 1
			elif s[low] == '2':
				count2 -= 1
			else:
				count3 -= 1
			low += 1
	if min_len == 200001:
		print(0)
	else:
		print(min_len)


from math import inf
t = int(input())
for _ in range(t):
	a = [int(i) - 1 for i in list(input().strip())]
	n = len(a)
	count = [0 for _ in range(3)]
	lo = 0
	hi = 0
	size = inf
	while hi < n:
		count[a[hi]] += 1
		while lo < hi and count[a[lo]] > 1:
			count[a[lo]] -= 1
			lo += 1
		if min(count) == 1:
			size = min(size, hi - lo + 1)
		hi += 1
	if size == inf:
		size = 0
	print(size)


for _ in range(int(input())):
	s = input()
	result = [0, 0, 0, 0]
	visited = [0, 0, 0, 0]
	min = 10000000
	ini = list(set(list(s)))
	if ini.count('1') + ini.count('3') + ini.count('2') != 3:
		print(0)
	else:
		for i in range(len(s)):
			result[int(s[i])] = i
			visited[int(s[i])] += 1
			if visited[1] > 0 and visited[2] > 0 and (visited[3] > 0):
				copy_result = result.copy()
				copy_result.sort()
				check = abs(copy_result[1] - copy_result[2]) + abs(copy_result[2] - copy_result[3])
				if check < min:
					min = check
		print(min + 1)


import sys
t = int(input())
for tc in range(t):
	arr = list(map(int, list(input())))
	n = len(arr)
	check = [0] * 4
	cnt = 0
	s = 0
	e = 0
	check[arr[0]] += 1
	cnt += 1
	ans = 300000
	while e < n - 1:
		if cnt < 3:
			e += 1
			check[arr[e]] += 1
			if check[arr[e]] == 1:
				cnt += 1
			if cnt == 3:
				ans = min(ans, e - s + 1)
		elif cnt == 3:
			s += 1
			check[arr[s - 1]] -= 1
			if check[arr[s - 1]] == 0:
				cnt -= 1
			if cnt == 3:
				ans = min(ans, e - s + 1)
	while s < n - 1:
		s += 1
		check[arr[s - 1]] = check[arr[s - 1]] - 1
		if check[arr[s - 1]] == 0:
			cnt = cnt - 1
		if cnt == 3:
			ans = min(ans, e - s + 1)
		else:
			break
	if ans == 300000:
		print(0)
	else:
		print(ans)


def mapit():
	temp = list(map(int, input().split()))
	return temp

def checker(left, mid1, mid2, right):
	if left != -1 and right != -1 and (left < right):
		if left < mid1 and mid1 < right or (left < mid2 and mid2 < right):
			return True
		else:
			return False
	else:
		return False

def solution():
	arr = [int(char) for char in input()]
	n = len(arr)
	one_left = [-1] * n
	one_right = [-1] * n
	two_left = [-1] * n
	two_right = [-1] * n
	three_left = [-1] * n
	three_right = [-1] * n
	for i in range(n):
		if arr[i] == 1:
			one_right[i] = one_left[i] = i
		elif arr[i] == 2:
			two_left[i] = two_right[i] = i
		else:
			three_left[i] = three_right[i] = i
	for (l, r) in zip(range(1, n), range(n - 2, -1, -1)):
		prev_l = l - 1
		prev_r = r + 1
		if one_left[prev_l] != -1 and one_left[l] == -1:
			one_left[l] = one_left[prev_l]
		if one_right[prev_r] != -1 and one_right[r] == -1:
			one_right[r] = one_left[prev_r]
		if two_left[prev_l] != -1 and two_left[l] == -1:
			two_left[l] = two_left[prev_l]
		if two_right[prev_r] != -1 and two_right[r] == -1:
			two_right[r] = two_left[prev_r]
		if three_left[prev_l] != -1 and three_left[l] == -1:
			three_left[l] = three_left[prev_l]
		if three_right[prev_r] != -1 and three_right[r] == -1:
			three_right[r] = three_left[prev_r]
	ans = float('Inf')
	for i in range(n):
		if checker(one_left[i], three_left[i], three_right[i], two_right[i]):
			ans = min(two_right[i] - one_left[i] + 1, ans)
		if checker(two_left[i], three_left[i], three_right[i], one_right[i]):
			ans = min(one_right[i] - two_left[i] + 1, ans)
		if checker(one_left[i], two_left[i], two_right[i], three_right[i]):
			ans = min(three_right[i] - one_left[i] + 1, ans)
		if checker(three_left[i], two_left[i], two_right[i], one_right[i]):
			ans = min(one_right[i] - three_left[i] + 1, ans)
		if checker(two_left[i], one_left[i], one_right[i], three_right[i]):
			ans = min(three_right[i] - two_left[i] + 1, ans)
		if checker(three_left[i], one_left[i], one_right[i], two_right[i]):
			ans = min(two_right[i] - three_left[i] + 1, ans)
	if ans == float('Inf'):
		print(0)
	else:
		print(ans)
	return
t = int(input())
while t:
	t -= 1
	solution()


T = int(input())

def findMin(s):
	k = 3
	n = len(s)
	st = 0
	end = 0
	cnt = {'1': 0, '2': 0, '3': 0}
	di = 0
	currlen = 0
	minlen = n
	startInd = -1
	while end < n:
		cnt[s[end]] += 1
		if cnt[s[end]] == 1:
			di += 1
		if di > k:
			while st < end and di > k:
				if cnt[s[st]] == 1:
					di -= 1
				cnt[s[st]] -= 1
				st += 1
		if di == k:
			while st < end and cnt[s[st]] > 1:
				cnt[s[st]] -= 1
				st += 1
			currlen = end - st + 1
			if currlen < minlen:
				minlen = currlen
				startInd = st
		end += 1
	if di != k:
		return 0
	return minlen
for t in range(T):
	string = input()
	print(findMin(string))


from sys import stdin, stdout
from math import ceil
t = int(stdin.readline())
for _ in range(t):
	s = input()
	one = -1
	two = -1
	three = -1
	ans = 10000007
	for i in range(len(s)):
		if one != -1 and two != -1 and (three != -1):
			ans = min(ans, max(one, two, three) - min(one, two, three) + 1)
		if s[i] == '1':
			one = i
		elif s[i] == '2':
			two = i
		if s[i] == '3':
			three = i
	if one != -1 and two != -1 and (three != -1):
		ans = min(ans, max(one, two, three) - min(one, two, three) + 1)
	if ans == 10000007:
		print(0)
	else:
		print(ans)


import sys
input = sys.stdin.readline
I = lambda : list(map(int, input().split()))
for _ in range(int(input())):
	s = input()
	an = 10 ** 9
	ar = [-1, -1, -1]
	i = 0
	while i < len(s) - 1:
		ar[int(s[i]) - 1] = i
		if -1 not in ar:
			an = min(an, max(ar) - min(ar) + 1)
		i += 1
	if -1 in ar:
		print(0)
	else:
		print(an)


mod = 1000000007
eps = 10 ** (-9)

def main():
	import sys
	input = sys.stdin.readline
	for _ in range(int(input())):
		S = input().rstrip('\n')
		N = len(S)
		l = 0
		cnt = [0, 0, 0]
		ans = N + 1
		for r in range(N):
			s = S[r]
			if s == '1':
				cnt[0] += 1
			elif s == '2':
				cnt[1] += 1
			else:
				cnt[2] += 1
			if cnt[0] > 0 and cnt[1] > 0 and (cnt[2] > 0):
				ans = min(ans, r - l + 1)
				while l < r:
					ss = S[l]
					if ss == '1':
						cnt[0] += -1
					elif ss == '2':
						cnt[1] += -1
					else:
						cnt[2] += -1
					l += 1
					if cnt[0] == 0 or cnt[1] == 0 or cnt[2] == 0:
						break
					else:
						ans = min(ans, r - l + 1)
		if ans == N + 1:
			print(0)
		else:
			print(ans)
main()


for t in range(int(input())):
	s = input()
	d = {'1': 0, '2': 0, '3': 0}
	(st, e, m) = (0, -1, 200001)
	for i in range(len(s)):
		d[s[i]] += 1
		e += 1
		if d['1'] > 0 and d['2'] > 0 and (d['3'] > 0):
			while 1:
				if d[s[st]] > 1:
					d[s[st]] -= 1
					st += 1
				else:
					break
			if e - st + 1 < m:
				m = e - st + 1
	if m == 200001:
		print(0)
	else:
		print(m)


tes = int(input())

def check(arr):
	for i in arr:
		if i <= 0:
			return False
	return True
for q in range(tes):
	a = input()
	s = {'1': 0, '2': 0, '3': 0}
	left = right = 0
	for (c, i) in enumerate(a):
		s[i] += 1
		if 0 not in s.values():
			right = c
			break
	if right - left < 1:
		print(0)
	else:
		m = right - left + 1
		s[a[left]] -= 1
		while right < len(a):
			while check(s.values()):
				s[a[left + 1]] -= 1
				left += 1
			m = min(m, right - left + 1)
			right += 1
			if right < len(a):
				s[a[right]] += 1
		print(m)


from math import ceil, gcd, factorial
from bisect import bisect_left as bl
from bisect import bisect_right as br
from array import array
from collections import Counter as ctr
from collections import deque as dq

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

def arr(a):
	return array('i', a)

def solve():
	for _ in range(int(input())):
		s = input()
		n = len(s)
		if '1' in s and '2' in s and ('3' in s):
			m = n
			i1 = s.index('1')
			i2 = s.index('2')
			i3 = s.index('3')
			b = s[::-1]
			l = n - max(b.index('1'), b.index('2'), b.index('3'))
			for i in range(l):
				if i > i1:
					i1 = s.index('1', i)
				elif i > i2:
					i2 = s.index('2', i)
				elif i > i3:
					i3 = s.index('3', i)
				ml = max(i1, i2, i3) - i + 1
				m = min(m, ml)
			print(m)
		else:
			print(0)
solve()


t = int(input())
for _ in range(t):
	s = input()
	found = False
	cur1 = s[0]
	cur2 = ''
	(l1, l2) = (0, 0)
	(l, r) = (0, 0)
	ans = 200001
	for (i, v) in enumerate(s):
		if v == cur1 and cur2:
			(cur1, cur2) = (cur2, cur1)
			l1 = i - 1
			l2 = i
		elif v == cur1:
			l1 = i
		elif v != cur1 and cur2 == '':
			l2 = i
			cur2 = v
		elif v != cur1 and v != cur2:
			ans = min(ans, i - l1 + 1)
			(cur1, cur2) = (cur2, v)
			l1 = i - 1
			l2 = i
			found = True
	if not found:
		print(0)
	else:
		print(ans)


def diff(a, b, c):
	return a != b and b != c and (c != a)
for _ in range(int(input())):
	s = input()
	n = len(s)
	a = [[s[0], 1]]
	for i in range(1, n):
		if s[i] == s[i - 1]:
			a[-1][1] += 1
		else:
			a.append([s[i], 1])
	l = len(a)
	ans = n
	f = 0
	for i in range(2, l):
		if diff(a[i][0], a[i - 1][0], a[i - 2][0]):
			ans = min(ans, 2 + a[i - 1][1])
			f = 1
	if not f:
		print(0)
	else:
		print(ans)


import math
t = int(input())
while t:
	s = input()
	n = len(s)
	dist_count = 3
	start = 0
	dict1 = {}
	count = 0
	min1 = 9999999
	for j in range(n):
		if s[j] in dict1:
			dict1[s[j]] += 1
		else:
			dict1[s[j]] = 1
		if dict1[s[j]] == 1:
			count += 1
		if count == dist_count:
			while dict1[s[start]] > 1:
				if dict1[s[start]] > 1:
					dict1[s[start]] -= 1
				start += 1
			min1 = min(min1, j - start + 1)
	if min1 == 9999999:
		min1 = 0
	print(min1)
	t -= 1


import queue
t = int(input())

def cnt(d):
	c = 0
	for i in d:
		c += d[i] > 0
	return c
while t:
	s = input()
	n = len(s)
	d = {'1': 0, '2': 0, '3': 0}
	(i, j) = (0, 0)
	inf = 10000000
	ans = inf
	while j < n:
		if cnt(d) == 3:
			while cnt(d) == 3:
				d[s[i]] -= 1
				i += 1
			ans = min(ans, j - i + 1)
		while j < n and cnt(d) < 3:
			d[s[j]] += 1
			j += 1
	if cnt(d) == 3:
		while cnt(d) == 3:
			d[s[i]] -= 1
			i += 1
		ans = min(ans, j - i + 1)
	if ans == inf:
		print('0')
	else:
		print(ans)
	t -= 1


from collections import defaultdict

def smallest(s1, s2):
	assert s2 != ''
	d = defaultdict(int)
	nneg = [0]

	def incr(c):
		d[c] += 1
		if d[c] == 0:
			nneg[0] -= 1

	def decr(c):
		if d[c] == 0:
			nneg[0] += 1
		d[c] -= 1
	for c in s2:
		decr(c)
	minlen = len(s1) + 1
	j = 0
	for i in range(len(s1)):
		while nneg[0] > 0:
			if j >= len(s1):
				return minlen
			incr(s1[j])
			j += 1
		minlen = min(minlen, j - i)
		decr(s1[i])
	return minlen
test = int(input())
l = 0
for i in range(test):
	s = input()
	x = smallest(s, '123')
	if x <= len(s):
		print(x)
	else:
		print(l)


import sys
import collections

def set_debug(debug_mode=False):
	if debug_mode:
		fin = open('input.txt', 'r')
		sys.stdin = fin
t = int(input())
for ti in range(1, t + 1):
	s = input()
	count = collections.Counter()
	unique = 0
	for x in '123':
		if count[x] == 0:
			unique += 1
		count[x] += 1
	l = 0
	res = float('inf')
	for r in range(len(s)):
		count[s[r]] -= 1
		if count[s[r]] == 0:
			unique -= 1
		while unique == 0:
			res = min(res, r - l + 1)
			count[s[l]] += 1
			if count[s[l]] == 1:
				unique += 1
			l += 1
	if res == float('inf'):
		print(0)
	else:
		print(res)


t = int(input())
for i in range(t):
	s = input()
	settri = [-1] * 3
	res = []
	for i in range(len(s)):
		settri[int(s[i]) - 1] = i
		if -1 not in settri:
			res.append(max(settri) - min(settri) + 1)
	if len(res) == 0:
		print(0)
	else:
		print(min(res))


N = int(input())
answers = []
for z in range(N):
	string = input().strip()
	numbers = []
	curr_len = 0
	result = len(string) + 1
	k = 0
	while k <= len(string):
		if len(numbers) == 3:
			result = min(result, curr_len)
			curr_len = 0
			numbers = []
			k -= 2
		if k == len(string):
			break
		if string[k] in numbers:
			if len(numbers) == 1:
				curr_len = 1
			elif string[k] == string[k - 1]:
				curr_len += 1
			else:
				curr_len = 2
		else:
			curr_len += 1
			numbers.append(string[k])
		k += 1
	if result == len(string) + 1:
		answers.append(0)
	else:
		answers.append(result)
for i in answers:
	print(i)


def rs():
	return input().strip()

def ri():
	return int(input())

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

def ia_to_s(a):
	return ' '.join([str(s) for s in a])
from itertools import chain, combinations

def solve(s):
	n = len(s)
	ans = n + 1
	i = 0
	while i < n:
		d = {}
		j = i
		while j < n and len(d) < 3:
			if s[j] in d:
				d[s[j]] += 1
			else:
				d[s[j]] = 1
			j += 1
		if len(d) == 3:
			while i < j and s[i] in d and (d[s[i]] > 1):
				d[s[i]] -= 1
				i += 1
			ans = min(ans, j - i)
		i = j
	return 0 if ans == n + 1 else ans

def powerset(iterable):
	s = list(iterable)
	return chain.from_iterable((combinations(s, r) for r in range(len(s) + 1)))

def solve1(s):
	n = len(s)
	ans = n + 1
	d = {}
	sets = list([set(st) for st in powerset(['1', '2', '3'])])
	for c in sets:
		if len(c) == 0:
			continue
		key = ''.join(sorted(c))
		d[key] = []
		if len(c) == 1:
			d[key].append(1 if s[0] == key else None)
			for i in range(1, n):
				d[key].append(1 if s[i] == key else None if d[key][i - 1] is None else d[key][i - 1] + 1)
		else:
			d[key].append(None)
			for i in range(1, n):
				if s[i] in c:
					s_key = ''.join(sorted(c.difference(s[i])))
					d[key].append(None if d[s_key][i - 1] is None else d[s_key][i - 1] + 1)
				else:
					d[key].append(None if d[key][i - 1] is None else d[key][i - 1] + 1)
	for i in range(n):
		if d['123'][i] is not None:
			ans = min(ans, d['123'][i])
	return 0 if ans == n + 1 else ans

def main():
	for _ in range(ri()):
		s = rs()
		print(solve1(s))
main()


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)


import copy
import fractions
import heapq
import math
import random
import sys
T = int(input())
for t in range(T):
	S = input()
	shortest = len(S) + 1
	counts = {'1': 0, '2': 0, '3': 0}
	(i, j) = (0, 0)
	while j < len(S):
		counts[S[j]] += 1
		j += 1
		while all((v >= 1 for v in counts.values())):
			shortest = min(shortest, j - i)
			counts[S[i]] -= 1
			i += 1
	if shortest <= len(S):
		print(shortest)
	else:
		print(0)


from collections import defaultdict
import sys
for _ in range(int(input())):
	str = input()
	n = len(str)
	dist_count = 3
	curr_count = defaultdict(int)
	(count, start, start_index) = (0, 0, -1)
	min_len = sys.maxsize
	for j in range(n):
		curr_count[str[j]] += 1
		if curr_count[str[j]] == 1:
			count += 1
		if count == dist_count:
			while curr_count[str[start]] > 1:
				if curr_count[str[start]] > 1:
					curr_count[str[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:
		print(0)
	else:
		print(min_len)


for _ in range(int(input())):
	s = input()
	le = len(s)
	if '1' not in s or '2' not in s or '3' not in s:
		print(0)
	else:
		s1 = s[0]
		(x, m) = (0, float('inf'))
		for i in range(1, le):
			if s[i] != s[i - 1]:
				if s[i] not in s1:
					s1 += s[i]
				else:
					x = i - 1
					s1 = s1[1:] + s[i]
			elif len(s1) == 1:
				x += 1
			if len(s1) == 3:
				m = min(m, i - x + 1)
				x = i - 1
				s1 = s1[1:]
		print(m)


def sel(a, b):
	if a == -1 or b == -1:
		return -1
	return max(a, b)

def solve(s):
	d = [[0] * (len(s) + 1) for i in range(3)]
	for j in range(3):
		d[j][len(s)] = -1
	for i in range(len(s) - 1, -1, -1):
		for j in range(3):
			d[j][i] = d[j][i + 1]
		v = ord(s[i]) - ord('1')
		d[v][i] = i
	best = 0
	for i in range(len(s)):
		t = -1
		if s[i] == '1':
			t = sel(d[1][i], d[2][i])
		elif s[i] == '2':
			t = sel(d[0][i], d[2][i])
		else:
			t = sel(d[0][i], d[1][i])
		if t != -1:
			l = t - i + 1
			if best == 0 or l < best:
				best = l
	return best
tests = int(input())
for test in range(tests):
	s = input()
	print(solve(s))


for _ in range(int(input())):
	s = input()
	if '1' not in s or '2' not in s or '3' not in s:
		print(0)
	else:
		(i1, x) = (0, s[0])
		l = []
		for i in range(1, len(s)):
			if s[i] != s[i - 1]:
				i1 = i - 1
				break
		i2 = i1 + 1
		for i in range(i1 + 2, len(s)):
			if s[i] != s[i2] and s[i] != s[i1]:
				l.append([i1, i2, i])
				i1 = i - 1
				i2 = i
			elif s[i] == s[i1]:
				i1 = i
			elif s[i] == s[i2]:
				i2 = i
		l1 = []
		for i in l:
			i.sort()
			l1.append(i[2] - i[0])
		print(min(l1) + 1)


for _ in range(int(input())):
	s = input()
	size = len(s)
	start = 0
	end = 0
	cnt = [0] * 4
	ans = float('inf')
	while end < size:
		c = s[end]
		cnt[int(c)] += 1
		while start <= end:
			if cnt[int(s[start])] == 1:
				break
			cnt[int(s[start])] -= 1
			start += 1
		if cnt[1] > 0 and cnt[2] > 0 and (cnt[3] > 0):
			ans = min(ans, end - start + 1)
		end = end + 1
	if ans == float('inf'):
		ans = 0
	print(ans)


from sys import stdin, stdout
t = int(input())
for _ in range(t):
	s = list(input())
	s = [int(k) for k in s]
	n = len(s)
	(l, r, c) = (0, 0, [0] * 4)
	res = n + 1
	for r in range(n):
		x = s[r]
		c[x] += 1
		while c[s[l]] > 1:
			c[s[l]] -= 1
			l += 1
		if c[1] >= 1 and c[2] >= 1 and (c[3] >= 1):
			res = min(res, r - l + 1)
	if res == n + 1:
		print(0)
	else:
		print(res)


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


t = int(input())
for i in range(t):
	s = str(input())
	ls = [-1, -1, -1]
	dist = 10 ** 21
	for j in range(len(s)):
		if s[j] == '1':
			ls[0] = j
		if s[j] == '2':
			ls[1] = j
		if s[j] == '3':
			ls[2] = j
		if -1 not in ls:
			dist = min(dist, max(ls) - min(ls) + 1)
	if dist > 10 ** 20:
		print(0)
	else:
		print(dist)


ipnl = lambda n: [int(input()) for _ in range(n)]
inp = lambda : int(input())
ip = lambda : [int(w) for w in input().split()]
for _ in range(inp()):
	s = input()
	if len(set(list(s))) < 3:
		print(0)
		continue
	x = []
	y = []
	prev = -1
	for i in s:
		if i != prev:
			x.append(int(i))
			y.append(1)
		else:
			y[-1] += 1
		prev = i
	mn = float('inf')
	for i in range(1, len(x) - 1):
		if sum(x[i - 1:i + 2]) == 6:
			mn = min(mn, y[i] + 2)
	print(mn)


from bisect import bisect
t = int(input())
out = ''
while t > 0:
	t -= 1
	s = input()
	n = len(s)
	answer = float('inf')
	keep = [[], [], []]
	for i in range(n):
		keep[int(s[i]) - 1].append(i)
	for i in range(1, n - 1):
		a = (int(s[i]) - 2) % 3
		b = int(s[i]) % 3
		in_a = bisect(keep[a], i)
		in_b = bisect(keep[b], i)
		if len(keep[a]) != in_a and in_b > 0:
			answer = min(answer, abs(keep[a][in_a] - i) + abs(keep[b][in_b - 1] - i) + 1)
		if in_a > 0 and len(keep[b]) != in_b:
			answer = min(answer, abs(keep[a][in_a - 1] - i) + abs(keep[b][in_b] - i) + 1)
	out += f"{(answer if answer != float('inf') else 0)}\n"
print(out)


from sys import stdin, stdout
import collections

def minWindow(s, t):
	(need, missing) = (collections.Counter(t), len(t))
	i = I = J = 0
	for (j, c) in enumerate(s, 1):
		missing -= need[c] > 0
		need[c] -= 1
		if not missing:
			while i < j and need[s[i]] < 0:
				need[s[i]] += 1
				i += 1
			if not J or j - i <= J - I:
				(I, J) = (i, j)
	return J - I

def main():
	for _ in range(int(stdin.readline())):
		S = stdin.readline().strip()
		print(minWindow(S, '123'))
main()


from sys import stdin, stdout
LI = lambda : list(map(int, input().split()))
MAP = lambda : map(int, input().split())
IN = lambda : int(input())
S = lambda : input()
import math
from collections import Counter

def solve():
	s = S()
	a = []
	b = []
	c = 1
	x = len(s) + 1
	for i in range(1, len(s)):
		if s[i] == s[i - 1]:
			c += 1
		else:
			a.append(int(s[i - 1]))
			b.append(c)
			c = 1
	a.append(int(s[-1]))
	b.append(c)
	for i in range(1, len(a) - 1):
		if a[i - 1] != a[i + 1]:
			x = min(x, b[i] + 2)
	if x == len(s) + 1:
		print(0)
	else:
		print(x)
for i in range(IN()):
	solve()


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)


T = int(input())
while T > 0:
	arr = input()
	dic = {}
	start = 0
	res = float('inf')
	for i in range(len(arr)):
		dic[arr[i]] = i
		if len(dic) == 3:
			while start < i:
				res = min(res, i - start + 1)
				if dic[arr[start]] == start:
					dic.pop(arr[start])
					start += 1
					break
				start += 1
	if res == float('inf'):
		print(0)
	else:
		print(res)
	T -= 1


def find(arr, ind):
	s = 0
	e = len(arr) - 1
	ans = -1
	while 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
	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)
		if x == -1 or y == -1:
			continue
		ans = min(ans, max(x, y) - i + 1)
	if ans == 9999999999:
		print(0)
	else:
		print(ans)


def cnt(i, j):
	return b[j - 1] - b[i] + 2
ans = []
for _ in range(int(input())):
	inp = list(map(int, list(input())))
	k = 1
	a = []
	b = []
	for i in range(1, len(inp)):
		if inp[i] != inp[i - 1]:
			a.append(inp[i - 1])
			b.append(k)
			k = 1
		else:
			k += 1
	a.append(inp[-1])
	b.append(k)
	for i in range(1, len(b)):
		b[i] += b[i - 1]
	c = [0, 0, 0]
	y = [0, 0, 0]
	d = []
	for i in range(3):
		d.append([])
	i = 0
	c[a[0] - 1] = 1
	for k in range(3):
		if a[0] == k + 1:
			d[k].append(0)
	ansi = len(inp) + 1
	for j in range(1, len(b)):
		c[a[j] - 1] = 1
		for k in range(3):
			if a[j] == k + 1:
				d[k].append(j)
		while c[0] and c[1] and c[2]:
			ansi = min(ansi, cnt(i, j))
			for k in range(3):
				if a[i] == k + 1:
					y[k] += 1
					if len(d[k]) == y[k]:
						c[k] = 0
					break
			i += 1
	if ansi == len(inp) + 1:
		ansi = 0
	ans.append(ansi)
print('\n'.join(map(str, ans)))


for _ in range(int(input())):
	b = input()
	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)


import math
for ii in range(int(input())):
	s = str(input())
	t = [int(i) for i in s]
	dic1 = {1: 0, 2: 0, 3: 0}
	i = 0
	j = 0
	ans = math.inf
	while i < len(t):
		while 0 in dic1.values() and j < len(t):
			dic1[t[j]] += 1
			j += 1
		if 0 not in dic1.values():
			ans = min(ans, j - i)
			dic1[t[i]] -= 1
			i += 1
		else:
			break
	if math.isfinite(ans):
		print(ans)
	else:
		print(0)


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)


def getN():
	return int(input())

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

def getList():
	return list(map(int, input().split()))
from collections import defaultdict, deque
from sys import exit
import math
import copy
from bisect import bisect_left
from heapq import *
import sys
INF = 10 ** 17
MOD = 998244353

def solve():
	s = input().strip()
	ones = [-INF]
	twos = [-INF]
	threes = [-INF]
	for (i, c) in enumerate(s):
		if c == '1':
			ones.append(i)
		elif c == '2':
			twos.append(i)
		else:
			threes.append(i)
	ones.append(INF)
	twos.append(INF)
	threes.append(INF)
	ans = INF * 3
	for third in threes[1:-1]:
		tgt = bisect_left(twos, third)
		(a, b) = (twos[tgt - 1], twos[tgt])
		tgt2 = bisect_left(ones, a)
		(c, d) = (ones[tgt2 - 1], ones[tgt2])
		if max(third, a, c) - min(third, a, c) < ans:
			ans = max(third, a, c) - min(third, a, c)
		if max(third, a, d) - min(third, a, d) < ans:
			ans = max(third, a, d) - min(third, a, d)
		tgt2 = bisect_left(ones, b)
		(c, d) = (ones[tgt2 - 1], ones[tgt2])
		if max(third, b, c) - min(third, b, c) < ans:
			ans = max(third, b, c) - min(third, b, c)
		if max(third, b, d) - min(third, b, d) < ans:
			ans = max(third, b, d) - min(third, b, d)
	if ans >= 200000:
		print(0)
	else:
		print(ans + 1)

def main():
	n = getN()
	for _ in range(n):
		solve()
main()


for _ in range(int(input())):
	s = input()
	d = {'1': 0, '2': 0, '3': 0}
	mn = 100000000000
	ln = 0
	j = 0
	fr = {'1': 0, '2': 0, '3': 0}
	for i in s:
		fr[i] += 1
	if fr['1'] == 0 or fr['2'] == 0 or fr['3'] == 0:
		print('0')
		continue
	for i in range(len(s)):
		d[s[i]] += 1
		ln += 1
		if d['1'] > 0 and d['2'] > 0 and (d['3'] > 0):
			mn = min(mn, ln)
			while d[s[j]] > 1:
				d[s[j]] -= 1
				j += 1
				ln -= 1
			mn = min(mn, ln)
	mn = min(mn, ln)
	print(mn)


t = int(input())
for i in range(t):
	a = list(input())
	b = []
	count = 0
	for j in range(len(a) - 1):
		count += 1
		if j == len(a) - 2:
			if a[j] != a[j + 1]:
				b.append([a[j], count])
				b.append([a[j + 1], 1])
			else:
				b.append([a[j], count + 1])
		elif a[j] != a[j + 1]:
			b.append([a[j], count])
			count = 0
	mn = 9999999999
	for k in range(1, len(b) - 1):
		if b[k][0] != b[k - 1][0] and b[k + 1][0] != b[k - 1][0] and (b[k][0] != b[k + 1][0]):
			if mn > b[k][1]:
				mn = b[k][1]
	if mn != 9999999999:
		print(mn + 2)
	else:
		print(0)


from collections import defaultdict
t = int(input())
for _ in range(t):
	s = input()
	n = len(s)
	c = n + 1
	d = defaultdict(int)
	l = 0
	for r in range(n):
		d[s[r]] += 1
		while d[s[l]] > 1:
			d[s[l]] -= 1
			l += 1
		if d['1'] > 0 and d['2'] > 0 and (d['3'] > 0):
			c = min(c, r - l + 1)
	if c > n:
		c = 0
	print(c)


from collections import deque as de
import math
from collections import Counter as cnt
from functools import reduce
from typing import MutableMapping
from itertools import groupby as gb
from fractions import Fraction as fr
from bisect import bisect_left as bl, bisect_right as br

def factors(n):
	return set(reduce(list.__add__, ([i, n // i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0)))

class My_stack:

	def __init__(self):
		self.data = []

	def my_push(self, x):
		return self.data.append(x)

	def my_pop(self):
		return self.data.pop()

	def my_peak(self):
		return self.data[-1]

	def my_contains(self, x):
		return self.data.count(x)

	def my_show_all(self):
		return self.data

	def isEmpty(self):
		return len(self.data) == 0
arrStack = My_stack()

def decimalToBinary(n):
	return bin(n).replace('0b', '')

def binarytodecimal(n):
	return int(n, 2)

def isPrime(n):
	if n <= 1:
		return False
	if n <= 3:
		return True
	if n % 2 == 0 or n % 3 == 0:
		return False
	i = 5
	while i * i <= n:
		if n % i == 0 or n % (i + 2) == 0:
			return False
		i = i + 6
	return True

def get_prime_factors(number):
	prime_factors = []
	while number % 2 == 0:
		prime_factors.append(2)
		number = number / 2
	for i in range(3, int(math.sqrt(number)) + 1, 2):
		while number % i == 0:
			prime_factors.append(int(i))
			number = number / i
	if number > 2:
		prime_factors.append(int(number))
	return prime_factors

def get_frequency(list):
	dic = {}
	for ele in list:
		if ele in dic:
			dic[ele] += 1
		else:
			dic[ele] = 1
	return dic

def Log2(x):
	return math.log10(x) / math.log10(2)

def isPowerOfTwo(n):
	return math.ceil(Log2(n)) == math.floor(Log2(n))

def ceildiv(x, y):
	return (x + y - 1) // y

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

def li():
	return list(map(int, input()))
t = int(input())
while t:
	t -= 1
	s = li()
	if len(set(s)) == 3:
		fre = []
		ele = []
		for (key, count) in gb(s):
			fre.append(len(list(count)))
			ele.append(key)
		mn = len(s)
		for i in range(1, len(fre) - 1):
			if ele[i - 1] != ele[i] != ele[i + 1] != ele[i - 1]:
				if fre[i] < mn:
					mn = fre[i]
		print(mn + 2)
	else:
		print(0)


import sys
from sys import stdin, stdout

def get_ints():
	return map(int, sys.stdin.readline().strip().split())

def get_list():
	return list(map(int, sys.stdin.readline().strip().split()))

def get_string():
	return sys.stdin.readline().strip()

def main():
	for t in range(int(input())):
		s = input()
		c = 1
		g = []
		g.append(s[0])
		f = 99999999
		n = len(s)
		for i in range(1, n):
			if s[i] in g:
				if s[i] != s[i - 1]:
					if len(set(g)) == 2 and s[i] not in g:
						c += 1
						f = min(f, c)
						g.pop(0)
						g.append(s[i - 1])
						g.append(s[i])
						c = 1
						c += 1
					else:
						c = 1
						c += 1
						g.pop(0)
						g.append(s[i])
				elif len(g) == 1:
					c = 1
				else:
					c += 1
			else:
				g.append(s[i])
				c += 1
			if len(set(g)) == 3:
				f = min(f, c)
				g.pop(0)
				c = 1
				c += 1
		if len(set(s)) != 3:
			print(0)
		else:
			print(f)
py2 = round(0.5)
if py2:
	from future_builtins import ascii, filter, hex, map, oct, zip
	range = xrange
import os, sys
from io import IOBase, BytesIO
BUFSIZE = 8192

class FastIO(BytesIO):
	newlines = 0

	def __init__(self, file):
		self._file = file
		self._fd = file.fileno()
		self.writable = 'x' in file.mode or 'w' in file.mode
		self.write = super(FastIO, self).write if self.writable else None

	def _fill(self):
		s = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
		self.seek((self.tell(), self.seek(0, 2), super(FastIO, self).write(s))[0])
		return s

	def read(self):
		while self._fill():
			pass
		return super(FastIO, self).read()

	def readline(self):
		while self.newlines == 0:
			s = self._fill()
			self.newlines = s.count(b'\n') + (not s)
		self.newlines -= 1
		return super(FastIO, self).readline()

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

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		if py2:
			self.write = self.buffer.write
			self.read = self.buffer.read
			self.readline = self.buffer.readline
		else:
			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))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


t = int(input())
for j in range(t):
	s = input()
	a = 0
	b = 0
	c = 0
	d = len(s)
	for i in range(len(s)):
		if s[i] == '1':
			a = i + 1
		elif s[i] == '2':
			b = i + 1
		elif s[i] == '3':
			c = i + 1
		if a != 0 and b != 0 and (c != 0):
			d = min(d, max(a, max(b, c)) - min(a, min(b, c)) + 1)
	if a == 0 or b == 0 or c == 0:
		print(0)
	else:
		print(d)


tt = int(input())
while tt > 0:
	tt -= 1
	s = input()
	n = len(s)
	(o, t, r) = ([0] * n, [0] * n, [0] * n)
	o[0] = t[0] = r[0] = -1
	ans = n + 1
	for i in range(n):
		if i > 0:
			o[i] = o[i - 1]
			t[i] = t[i - 1]
			r[i] = r[i - 1]
		if s[i] == '1':
			o[i] = i
		elif s[i] == '2':
			t[i] = i
		else:
			r[i] = i
		mn = min(o[i], t[i], r[i])
		if mn > -1:
			ans = min(ans, i - mn + 1)
	if ans == n + 1:
		ans = 0
	print(ans)


a = int(input())
for _ in range(a):
	s = input()
	ans = 10000000.0
	dp = {'1': -1, '2': -1, '3': -1}
	for (i, j) in enumerate(s):
		ss = ['1', '2', '3']
		if j == '1':
			dp[j] = i
		elif j == '2':
			dp[j] = i
		else:
			dp[j] = i
		ss.remove(j)
		if dp['1'] >= 0 and dp['2'] >= 0 and (dp['3'] >= 0):
			ans = min(ans, dp[j] - min(dp[ss[0]], dp[ss[1]]) + 1)
	if ans == 10000000.0:
		ans = 0
	print(ans)


for _ in range(int(input())):
	s = input()
	high = 0
	i = 0
	try:
		while True:
			count = 0
			n = int(s[i])
			i += 1
			while True:
				next = int(s[i])
				if n == next:
					break
				if next == int(s[i + 1]):
					count += 1
					i += 1
				elif int(s[i + 1]) == n:
					break
				else:
					if count + 3 < high or high == 0:
						high = count + 3
					break
	except IndexError:
		print(high)


T = int(input())
for _ in range(T):
	s = input()
	size = []
	trip = [-1, -1, -1]
	for i in range(len(s)):
		trip[int(s[i]) - 1] = i
		if -1 not in trip:
			size.append(max(trip) - min(trip) + 1)
	if len(size) == 0:
		print(0)
	else:
		print(min(size))


import sys

def shortestContiguousSubstringLen(a, n):
	s = e = 0
	minLen = 300000
	cnt = 0
	d = {}
	while e < n:
		cai = d.get(a[e], 0)
		if cai == 0:
			cnt += 1
			d[a[e]] = 1
		else:
			d[a[e]] = cai + 1
		if cnt == 3:
			while s < e and d[a[s]] > 1:
				d[a[s]] = d[a[s]] - 1
				s += 1
			length = e - s + 1
			if length < minLen:
				minLen = length
		e += 1
	if cnt < 3:
		return 0
	return minLen
t = int(sys.stdin.readline())
for _ in range(t):
	a = list(sys.stdin.readline().strip())
	n = len(a)
	res = shortestContiguousSubstringLen(a, n)
	print(res)


import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	s = input().rstrip()
	node1 = -1
	node2 = -1
	node3 = -1
	ans = 10 ** 9
	for (i, ch) in enumerate(s):
		if ch == '1':
			node1 = i
			frm = min(node1, node2, node3)
			if frm != -1:
				ans = min(ans, i - frm + 1)
		elif ch == '2':
			node2 = i
			frm = min(node1, node2, node3)
			if frm != -1:
				ans = min(ans, i - frm + 1)
		elif ch == '3':
			node3 = i
			frm = min(node1, node2, node3)
			if frm != -1:
				ans = min(ans, i - frm + 1)
	if ans == 10 ** 9:
		print(0)
	else:
		print(ans)


def isValid(s, mid):
	arr = [0] * 4
	for i in range(mid - 1):
		arr[int(s[i])] += 1
	for i in range(mid - 1, len(s)):
		arr[int(s[i])] += 1
		if arr[1] > 0 and arr[2] > 0 and (arr[3] > 0):
			return True
		arr[int(s[i - mid + 1])] -= 1
	return False

def getans(s):
	L = 3
	H = len(s)
	ans = 20000000
	while L <= H:
		mid = (L + H) // 2
		if isValid(s, mid):
			ans = min(ans, mid)
			H = mid - 1
		else:
			L = mid + 1
	if ans == 20000000:
		print(0)
	else:
		print(ans)
for _ in range(int(input())):
	s = input()
	getans(s)


T = int(input())
for _ in range(T):
	s = input()
	last1 = last2 = last3 = -1
	out = 200001
	for (i, c) in enumerate(s):
		if c == '1':
			last1 = i
		elif c == '2':
			last2 = i
		else:
			last3 = i
		if last1 == -1 or last2 == -1 or last3 == -1:
			continue
		out = min(out, i - min(last1, last2, last3) + 1)
		if out == 3:
			break
	if out <= 200000:
		print(out)
	else:
		print(0)


t = int(input())
for t0 in range(t):
	s = list(str(input()))
	for s0 in range(len(s)):
		s[s0] = int(s[s0])
	if s.count(1) != 0 and s.count(2) != 0 and (s.count(3) != 0):
		w = len(s)
		c = []
		a = []
		l = 0
		for i in range(1, len(s)):
			if s[i - 1] != s[i]:
				c.append(s[i - 1])
				a.append(i - l)
				l = i
		c.append(s[-1])
		a.append(i - l + 1)
		for j in range(len(c) - 2):
			if c[j] + c[j + 1] + c[j + 2] == 6 and a[j + 1] + 2 < w:
				w = a[j + 1] + 2
		print(w)
	else:
		print(0)


test = int(input())
while test:
	str = input()
	mi = 200000
	p1 = 0
	p2 = 0
	p3 = 0
	a = 0
	b = 0
	c = 0
	for i in range(0, len(str)):
		if str[i] == '1':
			p1 = i
			a = 1
		if str[i] == '2':
			p2 = i
			b = 1
		if str[i] == '3':
			p3 = i
			c = 1
		if a + b + c == 3:
			l = min(p1, p2, p3)
			r = max(p1, p2, p3)
			mi = min(mi, r - l)
	if mi == 200000:
		print('0')
	else:
		print(mi + 1)
	test -= 1


import math as mt
import sys, string
input = sys.stdin.readline
from collections import defaultdict
L = lambda : list(map(int, input().split()))
Ls = lambda : list(input().split())
M = lambda : map(int, input().split())
I = lambda : int(input())
t = I()
for _ in range(t):
	s = input().strip()
	l = []
	c = 1
	p = s[0]
	if len(s) <= 2:
		print(0)
	else:
		for i in range(1, len(s)):
			if s[i] == p:
				c += 1
			else:
				l.append([p, c])
				p = s[i]
				c = 1
		if s[-1] != s[-2]:
			l.append([p, 1])
		else:
			l.append([p, c + 1])
		ans = 10 ** 10
		if len(l) <= 2:
			print(0)
		else:
			for i in range(len(l) - 2):
				if sorted([int(l[i][0]), int(l[i + 1][0]), int(l[i + 2][0])]) == [1, 2, 3]:
					ans = min(ans, l[i + 1][1] + 2)
			if ans == 10 ** 10:
				print(0)
			else:
				print(ans)


import sys
import math
t = int(sys.stdin.readline().strip())
for i in range(t):
	s = sys.stdin.readline().strip()
	m = {}
	i = 0
	best = math.inf
	j = 0
	for i in range(0, len(s)):
		if s[i] in m:
			m[s[i]] += 1
		else:
			m[s[i]] = 1
		if len(m) == 3:
			while j < len(s):
				if m[s[j]] > 1:
					m[s[j]] -= 1
					j += 1
				else:
					break
			best = min(best, i - j + 1)
	if best == math.inf:
		print(0)
	else:
		print(best)


for tt in range(int(input())):
	s = input()
	last = 0
	val = [-1, -1, -1]
	val[int(s[last]) - 1] = 0
	inf = 99999999999999
	m = inf
	dist = 1
	n = len(s)
	for i in range(1, len(s)):
		val[int(s[i]) - 1] = i
		ok = last
		for k in range(ok, i):
			if val[int(s[k]) - 1] > k:
				last += 1
				dist -= 1
			else:
				break
		dist += 1
		if -1 not in val:
			m = min(m, dist)
	if m == inf:
		print(0)
	else:
		print(m)


for _ in range(int(input())):
	s = input()
	if '1' in s and '2' in s and ('3' in s):
		d1 = [-1] * (len(s) + 1)
		d2 = [-1] * (len(s) + 1)
		d3 = [-1] * (len(s) + 1)
		for i in range(len(s)):
			if s[i] == '1':
				d1[i + 1] = i
				d2[i + 1] = d2[i]
				d3[i + 1] = d3[i]
			elif s[i] == '2':
				d2[i + 1] = i
				d1[i + 1] = d1[i]
				d3[i + 1] = d3[i]
			else:
				d3[i + 1] = i
				d1[i + 1] = d1[i]
				d2[i + 1] = d2[i]
		ans = 10 ** 9
		for i in range(1, len(d2)):
			if d1[i] >= 0 and d2[i] >= 0 and (d3[i] >= 0):
				ans = min(ans, max(d1[i], d2[i], d3[i]) - min(d1[i], d2[i], d3[i]) + 1)
		print(ans)
	else:
		print(0)


for _ in range(int(input())):
	s = list(input())
	n = len(s)
	lis = [0] * 3
	l = r = 0
	ans = 10000000000
	while l < n and r < n:
		if min(lis) != 0:
			a = int(s[l]) - 1
			lis[a] -= 1
			l += 1
		else:
			a = int(s[r]) - 1
			lis[a] += 1
			r += 1
		if min(lis) != 0:
			ans = min(ans, r - l)
	while l < n:
		a = int(s[l]) - 1
		lis[a] -= 1
		l += 1
		if min(lis) != 0:
			ans = min(ans, r - l)
	if ans == 10000000000:
		print(0)
	else:
		print(ans)


t = int(input())
for i in range(t):
	s = input()
	lst = []
	l = 0
	minm = 9999999999999999999999
	a = b = c = 0
	for letter in s:
		lst.append(letter)
		l = l + 1
		if letter == '1':
			a = 1
		elif letter == '2':
			b = 1
		elif letter == '3':
			c = 1
		if letter == lst[0] and l > 1:
			lst.pop(0)
			l = l - 1
		while l > 1 and lst[0] == lst[1]:
			lst.pop(0)
			l = l - 1
		if a == 1 and b == 1 and (c == 1):
			if l < minm:
				minm = l
			anew = [lst[l - 2], lst[l - 1]]
			lst = anew
			l = 2
			a = 0
			b = 0
			c = 0
			if lst[0] == '1':
				a = 1
			elif lst[0] == '2':
				b = 1
			elif lst[0] == '3':
				c = 1
			if lst[1] == '1':
				a = 1
			elif lst[1] == '2':
				b = 1
			elif lst[1] == '3':
				c = 1
	if minm > 99999999999999999999:
		print(0)
	else:
		print(minm)


from sys import stdin
input = lambda : stdin.readline().strip()
from math import ceil, sqrt, factorial, gcd
from collections import deque
for _ in range(int(input())):
	s = list(input())
	m = float('infinity')
	flag = 0
	x = 0
	new = set()
	for i in range(len(s)):
		if len(new) == 0 or len(new) == 1:
			if s[i] in new:
				pass
			else:
				new.add(s[i])
				x += 1
		elif len(new) == 2:
			if s[i] in new and s[i] == s[i - 1]:
				x += 1
			elif s[i] in new and s[i] != s[i - 1]:
				x = 2
			else:
				x += 1
				m = min(m, x)
				new = set()
				new.add(s[i])
				new.add(s[i - 1])
				x = 2
	if m == float('infinity'):
		print(0)
	else:
		print(m)


import math
ans = []
for i in range(int(input())):
	s = input()
	la = -10000000000.0
	lb = -10000000000.0
	lc = -10000000000.0
	an = 10000000000.0
	for c in range(len(s)):
		if s[c] == '1':
			la = c
		if s[c] == '2':
			lb = c
		if s[c] == '3':
			lc = c
		if la >= 0 and lb >= 0 and (lc >= 0):
			an = min(an, c - min(la, lb, lc) + 1)
	ans += [an] if an != 10000000000.0 else [0]
for an in ans:
	print(an)


t = int(input())
for i in range(0, t):
	s = input()
	d = {1: 0, 2: 0, 3: 0}
	j = 0
	k = 0
	min = 10 ** 8
	while j < len(s):
		if s[j] == '1':
			d[1] += 1
		elif s[j] == '2':
			d[2] += 1
		else:
			d[3] += 1
		if d[1] >= 1 and d[2] >= 1 and (d[3] >= 1):
			for x in range(k, j - 1):
				if s[x] == '1':
					d[1] -= 1
				elif s[x] == '2':
					d[2] -= 1
				else:
					d[3] -= 1
				if d[1] < 1 or d[2] < 1 or d[3] < 1:
					y = x
					break
			if j - y + 1 < min:
				min = j - y + 1
			k = y + 1
		j += 1
	if min == 10 ** 8:
		print(0)
	else:
		print(min)


def solve(k):
	index1 = None
	index2 = None
	index3 = None
	miniDistance = len(k)
	for (i, j) in enumerate(k):
		if j == '1':
			index1 = i
		elif j == '2':
			index2 = i
		elif j == '3':
			index3 = i
		if index1 == None or index2 == None or index3 == None:
			continue
		else:
			cmp = max(index1, index2, index3) - min(index1, index2, index3) + 1
			if cmp < miniDistance:
				miniDistance = cmp
	if index1 == None or index2 == None or index3 == None:
		return 0
	else:
		return miniDistance
n = int(input())
for x in range(n):
	print(solve(input()))


from sys import stdin
import bisect
inp = lambda : stdin.readline().strip()

def binarySearch(array, x):
	i = bisect.bisect_left(array, x)
	if i == 0:
		return array[i]
	elif i == len(array):
		return array[i - 1]
	elif abs(array[i] - x) < abs(array[i - 1] - x):
		return array[i]
	else:
		return array[i - 1]
t = int(inp())
for _ in range(t):
	a = inp()
	ones = []
	twos = []
	threes = []
	for i in range(len(a)):
		if a[i] == '1':
			ones.append(i)
		elif a[i] == '2':
			twos.append(i)
		else:
			threes.append(i)
	ans = 200001
	if not ones or not twos or (not threes):
		print(0)
		continue
	for i in ones:
		x = binarySearch(twos, i)
		y = binarySearch(threes, i)
		a1 = [x, y, i]
		a1.sort()
		ans = min(ans, a1[2] - a1[0])
	for i in twos:
		x = binarySearch(ones, i)
		y = binarySearch(threes, i)
		a1 = [x, y, i]
		a1.sort()
		ans = min(ans, a1[2] - a1[0])
	for i in threes:
		x = binarySearch(twos, i)
		y = binarySearch(ones, i)
		a1 = [x, y, i]
		a1.sort()
		ans = min(ans, a1[2] - a1[0])
	print(ans + 1)


z = input
for _ in range(int(z())):
	s = z()
	m = 0
	l = [-1] * 3
	for i in range(len(s)):
		l[int(s[i]) - 1] = i
		if l[0] > -1 and l[1] > -1 and (l[2] > -1):
			if m == 0:
				m = max(l) - min(l) + 1
			else:
				m = min(m, max(l) - min(l) + 1)
	print(m)


for _ in range(int(input())):
	string = input()
	mydic = {'1': [], '2': [], '3': []}
	all_index = {}
	c1 = -1
	c2 = -1
	c3 = -1
	diff = 1000000000000000000000000000000000000000000000000000000000
	flag = True
	for i in range(len(string)):
		if string[i] == '1':
			c1 = i
			all_index[i] = [c1, c2, c3]
			a = max(all_index[i])
			b = min(all_index[i])
			if b == -1:
				flag = False
			else:
				flag = True
				mydiff = a - b
				if mydiff < diff:
					diff = mydiff
		elif string[i] == '2':
			c2 = i
			all_index[i] = [c1, c2, c3]
			a = max(all_index[i])
			b = min(all_index[i])
			if b == -1:
				flag = False
			else:
				flag = True
				mydiff = a - b
				if mydiff < diff:
					diff = mydiff
		elif string[i] == '3':
			c3 = i
			all_index[i] = [c1, c2, c3]
			a = max(all_index[i])
			b = min(all_index[i])
			if b == -1:
				flag = False
			else:
				flag = True
				mydiff = a - b
				if mydiff < diff:
					diff = mydiff
	if flag:
		print(diff + 1)
	else:
		print(0)


def solve(s):
	count = [0, 0, 0]
	l = 0
	r = 0
	res = 0
	while r < len(s):
		while min(count) == 0:
			count[int(s[r]) - 1] += 1
			r += 1
			if r == len(s):
				break
		if min(count) == 0:
			return res
		while min(count) > 0:
			count[int(s[l]) - 1] -= 1
			l += 1
			if l == r:
				break
		res = sum(count) + 1 if res == 0 else min(res, sum(count) + 1)
	return res
assert solve('123') == 3
assert solve('12222133333332') == 3
assert solve('112233') == 4
assert solve('332211') == 4
assert solve('12121212') == 0
assert solve('') == 0
assert solve('333333') == 0
assert solve('31121') == 4
T = int(input())
for _ in range(T):
	s = input().strip()
	print(solve(s))


import math
import sys
from collections import Counter
from collections import defaultdict
input = sys.stdin.readline

def solve():
	s = input().strip('\n')
	n = len(s)
	d = Counter(s)
	if len(d) < 3:
		print(0)
		return
	dis = 3
	s1 = 0
	si = -1
	min1 = pow(10, 9)
	count = 0
	d1 = defaultdict(int)
	for j in range(n):
		d1[s[j]] += 1
		if d1[s[j]] == 1:
			count += 1
		if count == 3:
			while d1[s[s1]] > 1:
				if d1[s[s1]] > 1:
					d1[s[s1]] -= 1
				s1 += 1
			length = j - s1 + 1
			if min1 > length:
				min1 = length
				si = s1
	print(min1)
for _ in range(int(input())):
	solve()


import sys
from sys import stdin, stdout
for _ in range(int(stdin.readline())):
	s = str(stdin.readline())
	n = len(s)
	(a, b, c) = (-1, -1, -1)
	l = 500000000000
	for i in range(n):
		if s[i] == '1':
			a = i
		elif s[i] == '2':
			b = i
		elif s[i] == '3':
			c = i
		if a >= 0 and b >= 0 and (c >= 0):
			l = min(l, max({a, b, c}) - min({a, b, c}) + 1)
	if l == 500000000000:
		print(0)
	else:
		print(l)


for _ in range(int(input())):
	has = input()
	maxs = 100000000000.0
	(i, j, k) = [-1, -1, -1]
	ans = maxs
	for (idx, val) in enumerate(has):
		if val == '1':
			i = idx
		if val == '2':
			j = idx
		if val == '3':
			k = idx
		if i > -1 and j > -1 and (k > -1):
			ans = min(ans, max(i, j, k) - min(i, j, k) + 1)
	print(ans if ans < maxs else 0)


for _ in range(int(input())):
	s = input()
	n = len(s)
	res = n
	tmp = [-n - 1] * 3
	for i in range(n):
		c = ord(s[i]) - ord('1')
		tmp[c] = i
		res = min(res, i - min(tmp) + 1)
	if min(tmp) < 0:
		res = 0
	print(res)


import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	string = list(input().rstrip())
	tmp = [0, 0, 0, 0]
	cnt = dict()
	l = r = 0
	length = res = len(string)
	fin = False
	while 1:
		if len(cnt) > 2:
			res = min(r - l, res)
			fin = True
			if res == 3:
				break
			tmp[int(string[l])] -= 1
			if tmp[int(string[l])] > 0:
				cnt[string[l]] -= 1
			else:
				cnt.pop(string[l])
			l += 1
			pass
		elif r == length:
			break
		else:
			tmp[int(string[r])] += 1
			if tmp[int(string[r])] == 1:
				cnt[string[r]] = 1
			else:
				cnt[string[r]] += 1
			r += 1
	print(res if fin else 0)


for _ in range(int(input())):
	n = input()
	i1 = i2 = i3 = -1
	l = len(n)
	m = l + 1
	z = False
	for i in range(l):
		if n[i] == '1':
			i1 = i
		elif n[i] == '2':
			i2 = i
		elif n[i] == '3':
			i3 = i
		if i1 >= 0 and i2 >= 0 and (i3 >= 0):
			k = max(i1, i2, i3) - min(i1, i2, i3)
			if m > k:
				m = k
				z = True
	if z:
		print(m + 1)
	else:
		print(0)


t = int(input())
for i in range(t):
	s = input()
	l = len(s)
	i1 = -1
	i2 = -1
	i3 = -1
	l2 = l + 1
	for i in range(l):
		a = int(s[i])
		if a == 1:
			i1 = i
			if i2 != -1 and i3 != -1:
				l1 = max(abs(i3 - i1) + 1, abs(i3 - i2) + 1, abs(i2 - i1) + 1)
				l2 = min(l1, l2)
				if i1 < i2 and i1 < i3:
					i1 = -1
				elif i2 < i1 and i2 < i3:
					i2 = -1
				elif i3 < i1 and i3 < i2:
					i3 = -1
		elif a == 2:
			i2 = i
			if i1 != -1 and i3 != -1:
				l1 = max(abs(i3 - i1) + 1, abs(i3 - i2) + 1, abs(i2 - i1) + 1)
				l2 = min(l1, l2)
				if i1 < i2 and i1 < i3:
					i1 = -1
				elif i2 < i1 and i2 < i3:
					i2 = -1
				elif i3 < i1 and i3 < i2:
					i3 = -1
		elif a == 3:
			i3 = i
			if i2 != -1 and i1 != -1:
				l1 = max(abs(i3 - i1) + 1, abs(i3 - i2) + 1, abs(i2 - i1) + 1)
				l2 = min(l1, l2)
				if i1 < i2 and i1 < i3:
					i1 = -1
				elif i2 < i1 and i2 < i3:
					i2 = -1
				elif i3 < i1 and i3 < i2:
					i3 = -1
	if l2 == l + 1:
		print(0)
	else:
		print(l2)


import math

def is_requirement_satisfied(req_map, found_map):
	for char in req_map:
		if found_map.get(char, 0) < req_map[char]:
			return False
	return True

def add_to_map(char, hash_map):
	hash_map[char] = hash_map.get(char, 0) + 1

def get_min_length(s, req_string):
	requirement_map = {}
	for char in req_string:
		requirement_map[char] = requirement_map.get(char, 0) + 1
	found_map = {}
	for char in requirement_map:
		found_map[char] = 0
	(left, right) = (0, 0)
	min_length = math.inf
	while right < len(s):
		add_to_map(s[right], found_map)
		while is_requirement_satisfied(requirement_map, found_map) and left <= right:
			window_size = right - left + 1
			if window_size < min_length:
				min_length = window_size
			found_map[s[left]] -= 1
			left += 1
		right += 1
	if min_length == math.inf:
		min_length = 0
	return min_length
t = int(input())
for i in range(t):
	print(get_min_length(input(), '123'))


for _ in range(int(input())):
	s = input()
	c = 1
	l = []
	i = -1
	for i in range(len(s) - 1):
		if s[i] == s[i + 1]:
			c = c + 1
		else:
			l.append([s[i], c])
			c = 1
	l.append([s[i + 1], c])
	m = 10000000
	for i in range(1, len(l) - 1):
		if l[i - 1][0] != l[i][0] and l[i][0] != l[i + 1][0] and (l[i - 1][0] != l[i + 1][0]):
			m = min(m, l[i][1] + 2)
	if m == 10000000:
		print(0)
		continue
	print(m)


t = int(input())
for i in range(t):
	s = input()
	one = 0
	two = 0
	three = 0
	for j in range(len(s)):
		if s[j] == '1':
			one = 1
		elif s[j] == '2':
			two = 1
		else:
			three = 1
		if one == 1 and two == 1 and (three == 1):
			break
	if one == 1 and two == 1 and (three == 1):
		lastone = None
		lasttwo = None
		lastthree = None
		minl = None
		truth = 0
		for j in range(len(s)):
			if s[j] == '1':
				lastone = j
			elif s[j] == '2':
				lasttwo = j
			else:
				lastthree = j
			if lastone != None and lasttwo != None and (lastthree != None):
				x = max(lastone, lasttwo, lastthree) - min(lastone, lasttwo, lastthree)
				if minl == None or x < minl:
					minl = x
			if minl == 2:
				print(3)
				truth = 1
				break
		if not truth:
			print(minl + 1)
	else:
		print(0)


import sys
input = sys.stdin.readline
Q = int(input())
Query = []
for _ in range(Q):
	Query.append(list(input().rstrip()))
for S in Query:
	Last = [-1] * 3
	ans = 10 ** 16
	for (i, s) in enumerate(S):
		n = int(s) - 1
		Last[n] = i
		if Last[0] != -1 and Last[1] != -1 and (Last[2] != -1):
			ans = min(ans, max(Last) - min(Last) + 1)
	if ans == 10 ** 16:
		print(0)
	else:
		print(ans)


from sys import stdin, stdout
stdin.readline

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

def it():
	return int(stdin.readline().strip())
from collections import defaultdict as dd, Counter as C, deque
from math import ceil, gcd, sqrt, factorial
from itertools import permutations
for _ in range(it()):
	l = list(input())
	s = set()
	ans = 2 * 100000 + 5
	flag = 0
	for i in range(len(l)):
		if l[i] == '1':
			one = i
			s.add(l[i])
		elif l[i] == '2':
			two = i
			s.add(l[i])
		else:
			three = i
			s.add(l[i])
		if len(s) == 3:
			flag = 1
			ans = min(ans, max(one, two, three) - min(one, two, three) + 1)
	if not flag:
		print(0)
	else:
		print(ans)


def main():
	line = input()
	one = -1
	two = -1
	three = -1
	length = len(line)
	for i in range(len(line)):
		if line[i] == '1':
			one = i
		elif line[i] == '2':
			two = i
		else:
			three = i
		if one >= 0 and two >= 0 and (three >= 0):
			length = min(max(one, two, three) - min(one, two, three), length)
	if one == -1 or two == -1 or three == -1:
		print(0)
		return
	print(length + 1)
t = int(input())
for i in range(t):
	main()


I = input
for _ in range(int(I())):
	n = list(input())
	o = []
	t = []
	tr = []
	lo = 0
	lt = 0
	ltr = 0
	for i in range(len(n)):
		if n[i] == '1':
			o.append(i + 1)
			lo += 1
		elif n[i] == '2':
			t.append(i + 1)
			lt += 1
		else:
			tr.append(i + 1)
			ltr += 1
	o.sort()
	t.sort()
	tr.sort()
	oi = 0
	ti = 0
	tri = 0
	count = 9e+18
	if lo == 0 or lt == 0 or ltr == 0:
		print(0)
	else:
		while True:
			m = max(o[oi], t[ti], tr[tri])
			s = min(o[oi], t[ti], tr[tri])
			if m - s + 1 < count:
				count = m - s + 1
			if s == o[oi]:
				oi += 1
			elif s == t[ti]:
				ti += 1
			else:
				tri += 1
			if tri >= ltr or ti >= lt or oi >= lo:
				break
		print(count)


import sys, math, re
input = lambda : sys.stdin.readline().strip()
for _ in range(int(input())):
	chrcount = {'1': 0, '2': 0, '3': 0}
	s = input()
	n = len(s)
	count = 0
	start = 0
	ans = 100000000000000000000
	for i in range(n):
		chrcount[s[i]] += 1
		if chrcount[s[i]] == 1:
			count += 1
		if count == 3:
			while chrcount[s[start]] > 1:
				if chrcount[s[start]] > 1:
					chrcount[s[start]] -= 1
				start += 1
			if ans > i - start + 1:
				ans = i - start + 1
	if ans == 100000000000000000000:
		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()
main()


for i in range(int(input())):
	s = input()
	if '1' in s and '2' in s and ('3' in s):
		ans = len(s)
	else:
		print(0)
		continue
	left = 1
	while left < len(s):
		length = 0
		while left + length < len(s) and s[left] == s[left + length]:
			length += 1
		extended = s[left - 1:left + length + 1]
		if '1' in extended and '2' in extended and ('3' in extended):
			ans = min(ans, length + 2)
		left = left + length
	print(ans)


import sys
sys.setrecursionlimit(10000)
from math import ceil

class Memoize:

	def __init__(self, f):
		self.f = f
		self.memo = {}

	def __call__(self, *args):
		if not args in self.memo:
			self.memo[args] = self.f(*args)
		return self.memo[args]

class Recurse(Exception):

	def __init__(self, *args, **kwargs):
		self.args = args
		self.kwargs = kwargs

def recurse(*args, **kwargs):
	raise Recurse(*args, **kwargs)

def tail_recursive(f):

	def decorated(*args, **kwargs):
		while True:
			try:
				return f(*args, **kwargs)
			except Recurse as r:
				args = r.args
				kwargs = r.kwargs
				continue
	return decorated
t = int(input())
for _ in range(t):
	s = input().strip()
	v = []
	cur = (s[0], 1)
	for i in range(1, len(s)):
		if s[i] == cur[0]:
			cur = (cur[0], cur[1] + 1)
		else:
			v.append(cur)
			cur = (s[i], 1)
	v.append(cur)
	if len(v) < 3:
		print(0)
		continue
	mn = 10000000
	for (x, y, z) in zip(v, v[1:], v[2:]):
		if len(set([x[0], y[0], z[0]])) == 3:
			mn = min(mn, 2 + y[1])
	print(mn if mn != 10000000 else 0)


t = int(input())
for _ in range(t):
	s = input()
	a1 = 0
	a2 = 0
	a3 = 0
	ans = []
	k = 1
	flag = 0
	for i in s:
		if i == '1':
			a1 = k
		elif i == '2':
			a2 = k
		else:
			a3 = k
		if a1 != 0 and a2 != 0 and (a3 != 0):
			ans.append(max(a1, a2, a3) - min(a1, a2, a3) + 1)
		k += 1
	if len(ans) == 0:
		print(0)
	else:
		print(min(ans))


t = int(input())
for i in range(t):
	s = input()
	a = [-1, -1, -1]
	l = len(s)
	k = 0
	res = 2000000000.0
	for j in range(l):
		a[ord(s[j]) - 50] = a[ord(s[j]) - 50] + 1
		while a[ord(s[k]) - 50] > 0:
			a[ord(s[k]) - 50] = a[ord(s[k]) - 50] - 1
			k = k + 1
		if a[0] >= 0 and a[1] >= 0 and (a[2] >= 0):
			res = min(res, j - k + 1)
	if res == 2000000000.0:
		res = 0
	print(res)


t = int(input())
for test in range(t):
	s = input()
	n = len(s)
	delta = [-1] * 3
	res = 100000000
	for i in range(n):
		if s[i] == '1':
			delta[0] = i
		elif s[i] == '2':
			delta[1] = i
		else:
			delta[2] = i
		if min(delta) >= 0:
			ans = max(delta) - min(delta) + 1
			res = min(res, ans)
	if res == 100000000:
		print(0)
	else:
		print(res)


tc = int(input().strip())

def solve():
	ss = input().strip()
	(i, j) = (0, 0)
	tables = [0] * 4
	min_length = float('inf')
	while j < len(ss):
		tables[ord(ss[j]) - ord('0')] += 1
		while tables[ord(ss[i]) - ord('0')] > 1:
			tables[ord(ss[i]) - ord('0')] -= 1
			i += 1
		if tables[1] >= 1 and tables[2] >= 1 and (tables[3] >= 1):
			min_length = min(min_length, j - i + 1)
		j += 1
	return 0 if min_length == float('inf') else min_length
for i in range(1, tc + 1):
	ans = solve()
	print(ans)


for _ in range(int(input())):
	s = input()
	count = 0
	se = set(s)
	if '1' not in se:
		print(0)
		continue
	elif '2' not in se:
		print(0)
		continue
	elif '3' not in se:
		print(0)
		continue
	first = s[0]
	i = 0
	ans = True
	count = 0
	ans1 = True
	fin = 1 + 2 + 3
	max1 = 9999999999999
	while i < len(s):
		num = 0
		fin = 1 + 2 + 3
		j = i
		ans1 = True
		count = 0
		while j < len(s) and s[j] == first:
			if ans1:
				num += 1
				ans1 = False
				fin -= int(s[j])
			j += 1
		ans1 = True
		count += 1
		temp = s[j]
		i = j
		first = temp
		while j < len(s) and s[j] == temp:
			count += 1
			if ans1:
				num += 1
				ans1 = False
				fin -= int(s[j])
			j += 1
		if j < len(s):
			num += 1
			fin -= int(s[j])
		count += 1
		if count < max1 and fin == 0:
			max1 = count
		if j >= len(s):
			break
	print(max1)


numOfRecords = input()
for i in range(0, int(numOfRecords)):
	integerStr = input()
	subStr = [-1] * 3
	minlength = 0
	for i in range(0, len(integerStr)):
		subStr[int(integerStr[i]) - 1] = i
		if min(subStr) == -1:
			continue
		if minlength == 0:
			minlength = max(subStr) - min(subStr) + 1
		elif minlength > max(subStr) - min(subStr):
			minlength = max(subStr) - min(subStr) + 1
	print(minlength)


strInp = lambda : input().strip().split()
intInp = lambda : list(map(int, strInp()))
for t in range(int(input())):
	s = list(input())
	d = [-1, -1, -1]
	ans = 10 ** 9 + 1
	for i in range(len(s)):
		if s[i] == '1':
			d[0] = i
		if s[i] == '2':
			d[1] = i
		if s[i] == '3':
			d[2] = i
		(a, b, c) = d
		if a != -1 and b != -1 and (c != -1):
			ans = min(ans, max(d) - min(d) + 1)
			md = min(d)
			if a == md:
				a = -1
			if b == md:
				b = -1
			if c == md:
				c = -1
	if ans == 10 ** 9 + 1:
		print(0)
	else:
		print(ans)


n = int(input())
for ti in range(n):
	s = input()
	h = []
	n = 0
	r = -1
	if '1' not in s or '2' not in s or '3' not in s:
		print('0')
		continue
	for i in range(len(s)):
		if s[i] not in h:
			h.append(s[i])
			n += 1
		if len(h) == 3:
			if r == -1:
				r = n
			elif n < r:
				r = n
			n = 0
			h = []
			h.append(s[i])
			n = 1
			if s[i - 1] not in h:
				h.append(s[i - 1])
				n += 1
		if s[i] in h and s[i - 1] == s[i]:
			n += 1
			continue
		elif s[i] in h and s[i - 1] != s[i]:
			n = 2
			continue
	print(r)


from collections import defaultdict
t = int(input())
for i in range(t):
	s = input()
	d = defaultdict(int)
	n = len(s)
	start = 0
	mini = 2000000
	c = 0
	for j in range(n):
		d[s[j]] += 1
		if d[s[j]] == 1:
			c += 1
		if c == 3:
			while d[s[start]] > 1:
				d[s[start]] -= 1
				start += 1
			a = j - start + 1
			if mini > a:
				mini = a
	if mini == 2000000:
		print('0')
	else:
		print(mini)


from math import ceil
t = int(input())
for _ in range(t):
	s = input()
	if s.count('1') == 0 or s.count('2') == 0 or s.count('3') == 0:
		print(0)
	else:
		(o, t, th) = (0, 0, 0)
		m = 9999999999
		for i in range(len(s)):
			if s[i] == '1':
				one = i + 1
				o = 1
			elif s[i] == '2':
				two = i + 1
				t = 1
			else:
				three = i + 1
				th = 1
			if t == 1 and o == 1 and (th == 1):
				first = max(one, two, three)
				second = min(one, two, three)
				if first - second < m:
					m = first - second
		print(m + 1)


def solve(s):
	if '1' not in s or '2' not in s or '3' not in s:
		return 0
	l = 0
	r = 1
	met = {'1': 0, '2': 0, '3': 0}
	met[s[l]] += 1
	best = 1000000000.0
	while r < len(s):
		if s[r] == s[l]:
			l += 1
			r = l + 1
			met = {'1': 0, '2': 0, '3': 0}
			met[s[l]] = 1
			met[s[r]] += 1
			continue
		else:
			met[s[r]] += 1
		if met['1'] and met['2'] and met['3']:
			best = min(best, r - l + 1)
		r += 1
	return best
[print(solve(input())) for _ in range(int(input()))]


t = int(input())
for _ in range(t):
	st = input()
	one = -1
	two = -1
	three = -1
	ans = float('inf')
	for ind in range(len(st)):
		if st[ind] == '1':
			one = ind
		elif st[ind] == '2':
			two = ind
		else:
			three = ind
		if one != -1 and two != -1 and (three != -1):
			ans = min(ans, max(one, two, three) - min(one, two, three) + 1)
	if ans == float('inf'):
		print(0)
	else:
		print(ans)


import math
import sys
from collections import defaultdict
from collections import deque
input = iter(sys.stdin.buffer.read().decode().splitlines()).__next__
ilele = lambda : map(int, input().split())
alele = lambda : list(map(int, input().split()))

def list2d(a, b, c):
	return [[c] * b for i in range(a)]

def list3d(a, b, c, d):
	return [[[d] * c for j in range(b)] for i in range(a)]
INF = 10 ** 18
MOD = 1000000000 + 7
for _ in range(int(input())):
	S = input()
	(a, b, c) = (None, None, None)
	Ans = 1000000000.0
	for i in range(len(S)):
		if S[i] == '1':
			a = i
		elif S[i] == '2':
			b = i
		else:
			c = i
		if a != None and b != None and (c != None):
			temp = i - min(a, b, c) + 1
			Ans = min(Ans, temp)
		if Ans == 3:
			break
	if Ans == None or Ans == 1000000000.0:
		print(0)
	else:
		print(Ans)


from sys import stdin, stdout
import sys
from math import *
for __ in range(int(input())):
	s = input()
	a = [0, 0, 0]
	x = 0
	y = 0
	ans = inf
	while x < len(s):
		if a[0] > 0 and a[1] > 0 and (a[2] > 0):
			ans = min(ans, y - x)
			a[int(s[x]) - 1] -= 1
			x += 1
		elif y < len(s):
			a[int(s[y]) - 1] += 1
			y += 1
		else:
			break
	if ans == inf:
		print(0)
	else:
		print(ans)


for nt in range(int(input())):
	s = input()
	n = len(s)
	arr = []
	c = 1
	prev = s[0]
	for i in range(1, n):
		if s[i] == prev:
			c += 1
		else:
			arr.append((prev, c))
			prev = s[i]
			c = 1
	arr.append((prev, c))
	m = 10 ** 9
	for i in range(len(arr) - 2):
		if arr[i][0] != arr[i + 1][0] and arr[i][0] != arr[i + 2][0]:
			m = min(m, arr[i + 1][1] + 2)
	if m == 10 ** 9:
		print(0)
	else:
		print(m)


T = int(input())
while T:
	S = input()
	n = len(S)
	m = n + 1
	D = {}
	D['1'] = 0
	D['2'] = 0
	D['3'] = 0
	c = 0
	a = 0
	for i in range(n):
		if D[S[i]] == 0:
			c = c + 1
		D[S[i]] = D[S[i]] + 1
		if c == 3:
			while D[S[a]] > 1:
				if D[S[a]] > 1:
					D[S[a]] = D[S[a]] - 1
				a = a + 1
			m = min(m, i - a + 1)
	if m > n:
		print(0)
	else:
		print(m)
	T = T - 1


no_of_chars = 256

def findSubStr(string, pat):
	len1 = len(string)
	len2 = 3
	if len1 < len2:
		return 0
	hash_pat = [0] * no_of_chars
	hash_str = [0] * no_of_chars
	for i in range(3):
		hash_pat[ord(pat[i])] += 1
	(start, start_index, min_len) = (0, -1, float('inf'))
	count = 0
	for j in range(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 0
	else:
		return min_len
cases = int(input())
for _ in range(cases):
	s = input()
	t = '123'
	print(findSubStr(s, t))


no_of_chars = 256

def findSubString(string, pat):
	count = 0
	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'))
	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]
t = int(input())
while t > 0:
	t -= 1
	s = str(input())
	if '1' not in s:
		print(0)
	elif '2' not in s:
		print(0)
	elif '3' not in s:
		print(0)
	else:
		dum = findSubString(s, '123')
		ans = len(dum)
		print(ans)


def ternary_string(s):
	seen = [False, False, False]
	for i in s:
		if i == '1':
			seen[0] = True
		elif i == '2':
			seen[1] = True
		else:
			seen[2] = True
		if all(seen):
			break
	if not all(seen):
		return 0
	seen = [1, 0, 0, 0]
	best_length = len(s)
	start = end = 0
	while end < len(s):
		c = s[end]
		seen[int(c)] += 1
		while all(seen):
			best_length = min(best_length, end - start + 1)
			seen[int(s[start])] -= 1
			start += 1
		end += 1
	return best_length
t = int(input())
for tc in range(t):
	s = input()
	res = ternary_string(s)
	print(res)


from collections import Counter
t = int(input())
for _ in range(t):
	s = input()
	start = 0
	end = len(s) - 1
	count = Counter(s)
	if count['1'] == 0 or count['2'] == 0 or count['3'] == 0:
		print(0)
	else:
		ans = len(s)
		l_1 = l_2 = l_3 = -1
		for i in range(len(s)):
			if s[i] == '1':
				l_1 = i
			elif s[i] == '2':
				l_2 = i
			else:
				l_3 = i
			if l_1 != -1 and l_2 != -1 and (l_3 != -1):
				mi = min(l_1, l_2, l_3)
				ma = max(l_1, l_2, l_3)
				ans = min(ans, ma - mi + 1)
		print(ans)


import sys
import math
import heapq
import collections

def inputnum():
	return int(input())

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

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

def inputstring():
	return [x for x in input()]
t = int(input())
for q in range(t):
	s = inputstring()
	ans = 200001
	has1 = False
	has2 = False
	has3 = False
	ind1 = 0
	ind2 = 0
	ind3 = 0
	for i in range(len(s)):
		if s[i] == '1':
			has1 = True
			ind1 = i
		if s[i] == '2':
			has2 = True
			ind2 = i
		if s[i] == '3':
			has3 = True
			ind3 = i
		if not has1 or not has2 or (not has3):
			continue
		cur = max(max(ind1, ind2), ind3) - min(min(ind1, ind2), ind3) + 1
		ans = min(ans, cur)
	if ans == 200001:
		print(0)
	else:
		print(ans)


for _ in range(int(input())):
	s = input()
	(_1, _2, _3) = (-1, -1, -1)
	m = 2000000
	for i in range(len(s)):
		if s[i] == '1':
			_1 = i
		elif s[i] == '2':
			_2 = i
		else:
			_3 = i
		if _1 >= 0 and _2 >= 0 and (_3 >= 0):
			m = min(m, max([_1, _2, _3]) - min([_1, _2, _3]))
	if m == 2000000:
		print(0)
	else:
		print(m + 1)


for _ in range(int(input())):
	s = input()
	p1 = 0
	p2 = 0
	p3 = 0
	mi = 2000000
	(a, b, c) = (0, 0, 0)
	for i in range(len(s)):
		if s[i] == '1':
			p1 = i
			a = 1
		if s[i] == '2':
			p2 = i
			b = 1
		if s[i] == '3':
			p3 = i
			c = 1
		if a + b + c == 3:
			l = min(p1, p2, p3)
			r = max(p1, p2, p3)
			mi = min(mi, r - l)
	if mi == 2000000:
		print('0')
	else:
		print(mi + 1)


from collections import defaultdict
for _ in range(int(input())):
	s = input()
	n = len(s)
	dist_count = 3
	curr_count = defaultdict(lambda : 0)
	min_length = float('inf')
	count = 0
	start = 0
	for i in range(n):
		curr_count[s[i]] += 1
		if curr_count[s[i]] == 1:
			count += 1
		if count == dist_count:
			min_length = min(min_length, i - start + 1)
			while count == dist_count:
				min_length = min(min_length, i - start + 1)
				if curr_count[s[start]] == 1:
					count -= 1
				curr_count[s[start]] -= 1
				start += 1
	if min_length == float('inf'):
		print(0)
	else:
		print(min_length)


for _ in range(int(input())):
	s = list(input())
	l = 0
	r = 0
	fans = 1000000000.0
	cc = [0, 0, 0]
	while l < len(s):
		while r < len(s) and (cc[0] <= 0 or cc[1] <= 0 or cc[2] <= 0):
			if s[r] == '1':
				cc[0] += 1
			if s[r] == '2':
				cc[1] += 1
			if s[r] == '3':
				cc[2] += 1
			r += 1
		if cc[0] > 0 and cc[1] > 0 and (cc[2] > 0):
			fans = min(fans, r - l)
		if s[l] == '1':
			cc[0] -= 1
		if s[l] == '2':
			cc[1] -= 1
		if s[l] == '3':
			cc[2] -= 1
		l += 1
	if fans == 1000000000.0:
		fans = 0
	print(fans)


t = int(input())
for i in range(t):
	s = input()
	le = len(s)
	(l, r) = (0, 0)
	d = [0, 0, 0]
	d[int(s[0]) - 1] = 1
	ans = 0
	while True:
		while not all(d) and r != le - 1:
			r += 1
			d[int(s[r]) - 1] += 1
			if r == le - 1:
				break
		while l != le - 1:
			if all(d):
				if ans == 0:
					ans = r - l + 1
				else:
					ans = min(ans, r - l + 1)
				d[int(s[l]) - 1] -= 1
				l += 1
			else:
				break
		if r == le - 1 or l == le - 1:
			break
	print(ans)


t = int(input())
ans = []
for k in range(t):
	s = input()
	a = b = c = -1
	z = []
	for i in range(len(s)):
		if s[i] == '1':
			a = i
		elif s[i] == '2':
			b = i
		else:
			c = i
		if a > -1 and b > -1 and (c > -1):
			(x, y) = (min(a, b, c), max(a, b, c))
			z.append(y - x + 1)
	if len(z) == 0:
		ans.append(0)
	else:
		ans.append(min(z))
for k in ans:
	print(k)


mod = int(1000000000.0) + 7

def ip():
	return int(input())

def Ip():
	return map(int, input().split())
for _ in range(0, int(input())):
	s = input()
	n = len(s)
	l = [[0, 0, 0] for i in range(0, n)]
	ans = n + 1
	l[0] = [-1, -1, -1]
	l[0][int(s[0]) - 1] = 0
	for i in range(1, n):
		x = int(s[i]) - 1
		l[i] = l[i - 1]
		l[i][x] = i
		if -1 not in l[i]:
			ans = min(ans, i - min(l[i]) + 1)
	if ans == n + 1:
		print(0)
	else:
		print(ans)


INF = 10 ** 10

def Sum(d):
	return sum([1 for k in d.keys() if d[k] > 0])

def solve():
	s = input()
	n = len(s)
	S = 3
	d = {'1': 0, '2': 0, '3': 0}
	left = 0
	right = 0
	res = INF
	for left in range(n):
		while right < n and Sum(d) < S:
			d[s[right]] += 1
			right += 1
		if Sum(d) == S:
			res = min(res, right - left)
		if right == left:
			right += 1
		else:
			d[s[left]] -= 1
	return res
t = int(input())
ans = []
for i in range(t):
	ans.append(solve())
for a in ans:
	if a != INF:
		print(a)
	else:
		print(0)


def sol(s):
	if s == '123' or s == '213' or s == '312' or (s == '132') or (s == '231') or (s == '321'):
		return 3
	ans = float('inf')
	n = len(s)
	a = b = c = -1
	for i in range(n):
		if s[i] == '1':
			a = i
		if s[i] == '2':
			b = i
		if s[i] == '3':
			c = i
		if a >= 0 and b >= 0 and (c >= 0):
			x = min(a, b, c)
			y = max(a, b, c)
			ans = min(ans, y - x + 1)
	if ans == float('inf'):
		return 0
	return ans

def main():
	T = int(input())
	while T is not 0:
		s = input()
		print(sol(s))
		T -= 1
main()


import sys

def calc(a, b, c):
	n = len(arr)
	st = []
	ans = 9876543210
	for i in range(n):
		if arr[i] == a:
			if not st:
				st.append(arr[i])
			else:
				while st:
					st.pop()
				st.append(arr[i])
		elif arr[i] == b:
			if st:
				st.append(arr[i])
		elif arr[i] == c:
			if st and st[-1] == b:
				ans = min(ans, len(st) + 1)
				while st:
					st.pop()
			while st:
				st.pop()
	return ans
tc = int(sys.stdin.readline())
for _ in range(tc):
	arr = sys.stdin.readline().rstrip()
	temp = ['1', '2', '3']
	res = 9876543210
	for i in temp:
		for j in temp:
			for k in temp:
				if i != j and j != k and (i != k):
					res = min(res, calc(i, j, k))
	print(0 if res == 9876543210 else res)


def flag():
	fla = True
	for key in dic:
		if dic[key] < 1:
			fla = False
	return fla
for _ in range(int(input())):
	s = str(input())
	i = 0
	j = -1
	dic = {}
	while len(dic) < 3 and j < len(s) - 1:
		j += 1
		if dic.get(s[j], 'k') == 'k':
			dic[s[j]] = 1
		else:
			dic[s[j]] += 1
	ans = j - i + 1
	if len(dic) < 3:
		print(0)
	elif ans == 3:
		print(ans)
	else:
		while i < j and j < len(s):
			if flag():
				dic[s[i]] -= 1
				i += 1
				if flag() and j - i + 1 < ans:
					ans = j - i + 1
			else:
				j += 1
				if j < len(s):
					dic[s[j]] += 1
					if flag() and j - i + 1 < ans:
						ans = j - i + 1
		print(ans)


import sys
for _ in range(int(input())):
	a = input()
	w = len(a)
	l = set(a)
	if len(l) < 3:
		print(0)
		continue
	p = sys.maxsize - 1
	(b, c, d) = (-1, -1, -1)
	for i in range(w):
		if a[i] == '1':
			b = i
		elif a[i] == '2':
			c = i
		elif a[i] == '3':
			d = i
		if b > -1 and c > -1 and (d > -1):
			t = max(b, max(c, d))
			o = min(b, min(c, d))
			jj = t + 1 - o
			p = min(p, jj)
	print(p)


(z, zz) = (input, lambda : list(map(int, z().split())))
zzz = lambda : [int(i) for i in stdin.readline().split()]
(szz, graph, mod, szzz) = (lambda : sorted(zz()), {}, 10 ** 9 + 7, lambda : sorted(zzz()))
from string import *
from re import *
from collections import *
from queue import *
from sys import *
from collections import *
from math import *
from heapq import *
from itertools import *
from bisect import *
from collections import Counter as cc
from math import factorial as f
from bisect import bisect as bs
from bisect import bisect_left as bsl
from itertools import accumulate as ac

def lcd(xnum1, xnum2):
	return xnum1 * xnum2 // gcd(xnum1, xnum2)

def prime(x):
	p = ceil(x ** 0.5) + 1
	for i in range(2, p):
		if x % i == 0 and x != 2 or x == 0:
			return 0
	return 1

def dfs(u, visit, graph):
	visit[u] = True
	for i in graph[u]:
		if not visit[i]:
			dfs(i, visit, graph)
num = int(z())
for _ in range(num):
	s = z()
	m = 0
	l = [-1] * 3
	for i in range(len(s)):
		l[int(s[i]) - 1] = i
		if l[0] > -1 and l[1] > -1 and (l[2] > -1):
			if m == 0:
				m = max(l) - min(l) + 1
			else:
				m = min(m, max(l) - min(l) + 1)
	print(m)


t = int(input())
for _ in range(t):
	s = input()
	d = [0 for i in range(3)]
	(gl, ll) = (10 ** 6, 10 ** 6)
	(l, r) = (0, 0)
	char = ['1', '2', '3']
	while l <= r:
		if d[0] < 1 or d[1] < 1 or d[2] < 1:
			if r < len(s):
				d[int(s[r]) - 1] += 1
				r += 1
			else:
				break
		else:
			ll = r - l
			gl = min(gl, ll)
			d[int(s[l]) - 1] -= 1
			l += 1
	if d[0] >= 1 and d[1] >= 1 and (d[2] >= 1):
		ll = r - l
		gl = min(gl, ll)
	if gl == 10 ** 6:
		print(0)
	else:
		print(gl)


t = int(input())
for _ in range(t):
	s = input()
	n = len(s)
	if n < 3:
		print(0)
	else:
		cnt = [0] * 3

		def getIdx(x):
			return ord(s[x]) - ord('1')

		def inc(x):
			cnt[getIdx(x)] += 1

		def dec(x):
			cnt[getIdx(x)] -= 1
		(i, j) = (0, 1)
		inc(i)
		inc(j)
		result = float('inf')
		while j < n:
			if cnt[0] == 0 or cnt[1] == 0 or cnt[2] == 0:
				j += 1
				if j == n:
					break
				inc(j)
			else:
				while cnt[0] > 0 and cnt[1] > 0 and (cnt[2] > 0):
					result = min(result, j - i + 1)
					dec(i)
					i += 1
		if result == float('inf'):
			result = 0
		print(result)


T = int(input().strip())
mmx = -10 ** 10
for t in range(T):
	s = input().strip()
	last = {'1': mmx, '2': mmx, '3': mmx}
	minl = -mmx
	for (ind, c) in enumerate(s):
		last[c] = ind
		minl = min(minl, max(last.values()) - min(last.values()))
	if minl < 10 ** 6:
		print(minl + 1)
	else:
		print(0)


import sys
import math
from collections import defaultdict, deque
import heapq
t = int(sys.stdin.readline())
for _ in range(t):
	s = list(sys.stdin.readline()[:-1])
	(o, t, th) = (0, 0, 0)
	n = len(s)
	(l, r) = (0, 0)
	ans = 10000000000.0
	z = True
	while r < n:
		while r < n and z:
			if s[r] == '1':
				o += 1
			elif s[r] == '2':
				t += 1
			else:
				th += 1
			if o > 0 and t > 0 and (th > 0):
				ans = min(ans, r - l + 1)
				z = False
			else:
				r += 1
		while not z and l < r:
			if s[l] == '1':
				o -= 1
			elif s[l] == '2':
				t -= 1
			else:
				th -= 1
			if o == 0 or t == 0 or th == 0:
				l += 1
				z = True
			else:
				l += 1
				ans = min(ans, r - l + 1)
		r += 1
	if ans == 10000000000.0:
		print(0)
	else:
		print(ans)


for _ in range(int(input())):
	s = list(input())
	if s.count('1') == 0 or s.count('2') == 0 or s.count('3') == 0:
		print(0)
		continue
	d = dict()
	d['1'] = -1
	d['2'] = -1
	d['3'] = -1
	m = 7 + 10 ** 9
	for i in range(len(s)):
		d[s[i]] = i
		for j in d:
			if d[j] == -1:
				break
		else:
			m = min(m, max(d.values()) - min(d.values()) + 1)
	print(m)


def smallestWindow(s, p):
	n = len(s)
	if n < len(p):
		return 0
	mp = [0] * 256
	start = 0
	ans = n + 1
	cnt = 0
	for i in p:
		mp[ord(i)] += 1
		if mp[ord(i)] == 1:
			cnt += 1
	j = 0
	i = 0
	while j < n:
		mp[ord(s[j])] -= 1
		if mp[ord(s[j])] == 0:
			cnt -= 1
			while cnt == 0:
				if ans > j - i + 1:
					ans = j - i + 1
					start = i
				mp[ord(s[i])] += 1
				if mp[ord(s[i])] > 0:
					cnt += 1
				i += 1
		j += 1
	if ans > n:
		return '0'
	return len(s[start:start + ans])
for i in range(int(input())):
	s = input()
	p = '123'
	result = smallestWindow(s, p)
	print(result)


for _ in range(int(input())):
	s = input()
	n = [0] * 4
	l = k = i = j = 0
	while True:
		if k < 3:
			if j == len(s):
				break
			b = int(s[j])
			j += 1
			k += n[b] == 0
			n[b] += 1
		else:
			if l == 0 or l > j - i:
				l = j - i
			a = int(s[i])
			n[a] -= 1
			k -= n[a] == 0
			i += 1
	print(l)


class Solver:

	def __init__(self, t):
		self.incorrect = set()
		self.count = dict()
		self.tracked = dict()
		for char in t:
			self.count[char] = self.count.get(char, 0) + 1
		for char in self.count.keys():
			self.incorrect.add(char)

	def eval(self):
		return len(self.incorrect) == 0

	def add(self, char):
		if char not in self.count:
			return
		self.tracked[char] = self.tracked.get(char, 0) + 1
		if self.tracked[char] >= self.count.get(char, 0):
			_ = self.incorrect.discard(char)
		else:
			self.incorrect.add(char)

	def remove(self, char):
		if char not in self.count:
			return
		self.tracked[char] -= 1
		if self.tracked[char] < self.count[char]:
			self.incorrect.add(char)

def minWindow(s, t):
	(i, j) = (0, 0)
	n = len(s)
	solver = Solver(t)
	if solver.eval():
		return ''
	minSize = n + 1
	(minLeft, minRight) = (-1, -1)
	while j < n:
		while j < n and (not solver.eval()):
			solver.add(s[j])
			j += 1
		if not solver.eval():
			break
		while solver.eval():
			if j - i < minSize:
				minSize = j - i
				(minLeft, minRight) = (i, j)
			solver.remove(s[i])
			i += 1
	if minSize == n + 1:
		return 0
	else:
		return minRight - minLeft
t = int(input())
for _ in range(t):
	s = input()
	t = '123'
	print(minWindow(s, t))


def sub(string, pattern):
	if len(string) < len(pattern):
		return 0
	hash_pattern = [0] * 256
	hash_string = [0] * 256
	for i in range(len(pattern)):
		hash_pattern[ord(pattern[i])] += 1
	(start, start_index, min_len) = (0, -1, float('inf'))
	count = 0
	for j in range(0, len(string)):
		hash_string[ord(string[j])] += 1
		if hash_pattern[ord(string[j])] != 0 and hash_string[ord(string[j])] <= hash_pattern[ord(string[j])]:
			count += 1
		if count == len(pattern):
			while hash_string[ord(string[start])] > hash_pattern[ord(string[start])] or hash_pattern[ord(string[start])] == 0:
				if hash_string[ord(string[start])] > hash_pattern[ord(string[start])]:
					hash_string[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 0
	return min_len

def main():
	t = int(input())
	while t:
		t -= 1
		s = input()
		print(sub(s, '123'))
main()


from collections import *
from bisect import *
from math import *
from heapq import *
import sys
input = sys.stdin.readline
t = int(input())
while t:
	t -= 1
	a = input().rstrip('\n')
	f = [-float('inf') for i in range(3)]
	ans = float('inf')
	for i in range(len(a)):
		z = int(a[i])
		f[z - 1] = max(f[z - 1], i)
		if min(f) != -float('inf'):
			ans = min(ans, max(f) - min(f) + 1)
	if ans < 0 or ans == float('inf'):
		print(0)
	else:
		print(ans)


from sys import stdin, stdout
from collections import Counter

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

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

def ip():
	return int(stdin.readline().strip())

def op(ans):
	return stdout.write(str(ans) + '\n')
from collections import defaultdict
no_of_chars = 256

def findSubString(string, pat):
	len1 = len(string)
	len2 = len(pat)
	if len1 < len2:
		return 0
	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 0
	return len(string[start_index:start_index + min_len])
t = ip()
for i in range(t):
	string = input()
	pat = '123'
	print(findSubString(string, pat))


import sys
input = sys.stdin.readline

def solve(S):
	if len(set(S)) < 3:
		return 0
	L = []
	cnt = 0
	prev = S[0]
	for s in S:
		if s == prev:
			cnt += 1
		else:
			L.append((prev, cnt))
			cnt = 1
		prev = s
	L.append((prev, cnt))
	ans = len(S)
	for i in range(len(L) - 2):
		num_set = set()
		for j in range(3):
			num_set.add(L[i + j][0])
		if len(num_set) == 3:
			ans = min(ans, L[i + 1][1] + 2)
	return ans

def main():
	t = int(input())
	for _ in range(t):
		S = [int(x) for x in list(input().strip())]
		ans = solve(S)
		sys.stdout.write(str(ans) + '\n')
main()


def main(s):
	if len(s) < 3:
		return 0
	counts = [0 for _ in range(3)]
	for i in range(3):
		counts[int(s[i]) - 1] += 1
	left = 0
	right = 2
	best_length = 0
	while True:
		if counts[0] * counts[1] * counts[2] != 0:
			length = right - left + 1
			if length < best_length or best_length == 0:
				best_length = length
		right += 1
		if right == len(s):
			return best_length
		counts[int(s[right]) - 1] += 1
		while counts[int(s[left]) - 1] > 1 and left < right:
			counts[int(s[left]) - 1] -= 1
			left += 1
t = int(input())
for _ in range(t):
	s = input()
	best_length = main(s)
	print(best_length)


n = int(input())
loop = 0
while loop != n:
	s = input()
	shortest = 200001
	(s1, s2) = (' ', ' ')
	len1 = 0
	for i in range(len(s)):
		letter = s[i]
		if s1 == ' ':
			s1 = letter
			len1 = 1
		elif letter == s1:
			len1 += 1
		elif s2 == ' ':
			(s2, s1) = (s1, letter)
			len1 = 2
		elif letter == s2:
			(s1, s2) = (letter, s1)
			len1 = 2
		else:
			shortest = min(shortest, len1 + 1)
			(s1, s2) = (letter, s1)
			len1 = 2
	if shortest == 200001:
		print(0)
	else:
		print(shortest)
	loop += 1


n = int(input())
for i in range(0, n):
	s = input().rstrip()
	x = list(s)
	L = []
	Q = []
	W = []
	for i in range(0, len(x)):
		if x[i] == '1':
			L.append(i)
		elif x[i] == '2':
			Q.append(i)
		else:
			W.append(i)
	if len(L) == 0 or len(Q) == 0 or len(W) == 0:
		print(0)
	else:
		l = []
		q = []
		w = []
		tot = 100000000000000000
		for i in range(0, len(L)):
			A = int(L[i])
			l.append(A)
			I = 0
			J = len(Q) - 1
			V_greater = -1
			while I <= J:
				m = (I + J) // 2
				if Q[m] < A:
					I = m + 1
				else:
					V_greater = Q[m]
					J = m - 1
			I = 0
			J = len(Q) - 1
			V_smaller = -1
			while I <= J:
				m = (I + J) // 2
				if Q[m] > A:
					J = m - 1
				else:
					V_smaller = Q[m]
					I = m + 1
			if V_greater != -1:
				q.append(V_greater)
			if V_smaller != -1:
				q.append(V_smaller)
			I = 0
			J = len(W) - 1
			Vz_greater = -1
			while I <= J:
				m = (I + J) // 2
				if W[m] < A:
					I = m + 1
				else:
					Vz_greater = W[m]
					J = m - 1
			I = 0
			J = len(W) - 1
			Vz_smaller = -1
			while I <= J:
				m = (I + J) // 2
				if W[m] > A:
					J = m - 1
				else:
					Vz_smaller = W[m]
					I = m + 1
			if Vz_greater != -1:
				w.append(Vz_greater)
			if Vz_smaller != -1:
				w.append(Vz_smaller)
			sVz_smaller = -1
			sVz_greater = -1
			if V_greater != -1:
				I = 0
				J = len(W) - 1
				while I <= J:
					m = (I + J) // 2
					if W[m] < A:
						I = m + 1
					else:
						sVz_greater = W[m]
						J = m - 1
			if V_smaller != -1:
				I = 0
				J = len(W) - 1
				while I <= J:
					m = (I + J) // 2
					if W[m] > A:
						J = m - 1
					else:
						sVz_smaller = W[m]
						I = m + 1
			if sVz_greater != -1:
				w.append(sVz_greater)
			if sVz_smaller != -1:
				w.append(sVz_smaller)
			if len(l) == 0 or len(q) == 0 or len(w) == 0:
				continue
			for k in range(0, len(l)):
				for m in range(0, len(q)):
					for N in range(0, len(w)):
						A = l[k]
						B = q[m]
						C = w[N]
						J = min(A, B, C)
						O = max(A, B, C)
						tot = min(tot, O - J)
			l = []
			q = []
			w = []
		print(tot + 1)


for t in range(int(input())):
	s = input()
	(i, j) = (0, 0)
	cnt = 0
	ans = float('inf')
	dic = {}
	while j < len(s):
		if len(dic) < 3:
			dic[s[j]] = dic.get(s[j], 0) + 1
		while len(dic) == 3:
			ans = min(ans, j - i + 1)
			dic[s[i]] -= 1
			if dic[s[i]] == 0:
				del dic[s[i]]
			i += 1
		j += 1
	print((0, ans)[ans < float('inf')])


for _ in range(int(input())):
	seq = input()
	length = len(seq)
	dictionary = {}
	result = float('inf')
	for i in range(length):
		dictionary[seq[i]] = i
		if len(dictionary) == 3:
			minn = float('inf')
			maxx = 0
			for i in dictionary:
				v = dictionary[i]
				if v < minn:
					minn = v
				if v > maxx:
					maxx = v
			res = maxx - minn + 1
			if res < result:
				result = res
	if result == float('inf'):
		print(0)
	else:
		print(result)


t = int(input())
for _ in range(t):
	a = list(map(int, list(input())))
	count = [1]
	u = [a[0]]
	k = 0
	for i in range(1, len(a)):
		if u[k] == a[i]:
			count[k] += 1
		else:
			u.append(a[i])
			count.append(1)
			k = k + 1
	minm = 200000
	flag = 0
	for i in range(len(u) - 2):
		if sorted(u[i:i + 3]) == [1, 2, 3]:
			if 2 + count[i + 1] <= minm:
				minm = 2 + count[i + 1]
				flag = 1
	if flag == 0:
		print(0)
	else:
		print(minm)


from math import *
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]
a = int(input())
for x in range(a):
	b = input()
	j = len(findSubString(b, '123'))
	print(j)


def solution():
	s = input()
	last1 = -1
	last2 = -1
	last3 = -1
	minLen = 300000
	for i in range(len(s)):
		c = s[i]
		if c == '1':
			last1 = i
		elif c == '2':
			last2 = i
		else:
			last3 = i
		if last1 > -1 and last2 > -1 and (last3 > -1):
			minLen = min(minLen, max(last1, last2, last3) - min(last1, last2, last3) + 1)
	print(0) if minLen == 300000 else print(minLen)
T = int(input())
for t in range(T):
	solution()


import sys
t = int(input())
for _ in range(t):
	d = {'1': 0, '2': 0, '3': 0}
	s = input()
	size = 0
	mini = sys.maxsize
	j = 0
	for i in range(len(s)):
		d[s[i]] += 1
		size += 1
		while d['1'] >= 1 and d['2'] >= 1 and (d['3'] >= 1) and (j < i):
			mini = min(mini, size)
			size -= 1
			d[s[j]] -= 1
			j += 1
			if mini == 3:
				break
		if mini == 3:
			break
	if mini == sys.maxsize:
		print(0)
	else:
		print(mini)


def solve():
	s = input()
	(ans, p1, p2, v) = (len(s) + 5, 0, 0, [0, 0, 0, 0])
	while p2 < len(s):
		v[int(s[p2])] += 1
		while v[1] and v[2] and v[3]:
			v[int(s[p1])] -= 1
			ans = min(ans, p2 - p1 + 1)
			p1 += 1
		p2 += 1
	if ans > len(s):
		print(0)
	else:
		print(ans)

def main():
	t = int(input())
	for i in range(0, t):
		solve()
main()


import sys

def I():
	return sys.stdin.readline().rstrip()
for tc in range(1, 1 + int(I())):
	s = I()
	neg = -200000000
	last = {'1': neg, '2': neg, '3': neg}
	mn = -neg
	for (i, c) in enumerate(s):
		last[c] = i
		mn = min(mn, 1 + max(last.values()) - min(last.values()))
	if mn == -neg:
		mn = 0
	print(mn)


from collections import defaultdict

def smallest(s1, s2):
	assert s2 != ''
	d = defaultdict(int)
	nneg = [0]

	def incr(c):
		d[c] += 1
		if d[c] == 0:
			nneg[0] -= 1

	def decr(c):
		if d[c] == 0:
			nneg[0] += 1
		d[c] -= 1
	for c in s2:
		decr(c)
	minlen = len(s1) + 1
	j = 0
	for i in range(len(s1)):
		while nneg[0] > 0:
			if j >= len(s1):
				return minlen
			incr(s1[j])
			j += 1
		minlen = min(minlen, j - i)
		decr(s1[i])
	return minlen
t = int(input())
for i1 in range(t):
	x = '123'
	y = input()
	num = [0, 0, 0, 0]
	for i2 in y:
		temp = int(i2)
		num[temp] += 1
	if num[1] == 0 or num[2] == 0 or num[3] == 0:
		print(0)
	else:
		print(smallest(y, x))


from heapq import heapify, heappush, heappop
import bisect
from math import pi
from collections import deque
from math import factorial
from math import log, ceil
from collections import defaultdict
from math import *
from sys import stdin, stdout
import itertools
import os
import sys
import threading
from collections import deque, Counter, OrderedDict, defaultdict
from heapq import *
from fractions import Fraction
mod = int(pow(10, 9) + 7)

def ii():
	return int(input())

def si():
	return str(input())

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

def li1():
	return list(mi())

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

def fsi():
	return str(stdin.readline())

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

def fli():
	return list(fmi())
abd = {'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4, 'f': 5, 'g': 6, 'h': 7, 'i': 8, 'j': 9, 'k': 10, 'l': 11, 'm': 12, 'n': 13, 'o': 14, 'p': 15, 'q': 16, 'r': 17, 's': 18, 't': 19, 'u': 20, 'v': 21, 'w': 22, 'x': 23, 'y': 24, 'z': 25}

def getKey(item):
	return item[0]

def sort2(l):
	return sorted(l, key=getKey)

def d2(n, m, num):
	return [[num for x in range(m)] for y in range(n)]

def isPowerOfTwo(x):
	return x and (not x & x - 1)

def decimalToBinary(n):
	return bin(n).replace('0b', '')

def ntl(n):
	return [int(i) for i in str(n)]

def powerMod(x, y, p):
	res = 1
	x %= p
	while y > 0:
		if y & 1:
			res = res * x % p
		y = y >> 1
		x = x * x % p
	return res
graph = defaultdict(list)
visited = [0] * 1000000
col = [-1] * 1000000

def bfs(d, v):
	q = []
	q.append(v)
	visited[v] = 1
	while len(q) != 0:
		x = q[0]
		q.pop(0)
		for i in d[x]:
			if visited[i] != 1:
				visited[i] = 1
				q.append(i)
		print(x)

def make_graph(e):
	d = {}
	for i in range(e):
		(x, y) = mi()
		if x not in d:
			d[x] = [y]
		else:
			d[x].append(y)
		if y not in d:
			d[y] = [x]
		else:
			d[y].append(x)
	return d

def gr2(n):
	d = defaultdict(list)
	for i in range(n):
		(x, y) = mi()
		d[x].append(y)
	return d

def connected_components(graph):
	seen = set()

	def dfs(v):
		vs = set([v])
		component = []
		while vs:
			v = vs.pop()
			seen.add(v)
			vs |= set(graph[v]) - seen
			component.append(v)
		return component
	ans = []
	for v in graph:
		if v not in seen:
			d = dfs(v)
			ans.append(d)
	return ans

def primeFactors(n):
	s = set()
	while n % 2 == 0:
		s.add(2)
		n = n // 2
	for i in range(3, int(sqrt(n)) + 1, 2):
		while n % i == 0:
			s.add(i)
			n = n // i
	if n > 2:
		s.add(n)
	return s

def find_all(a_str, sub):
	start = 0
	while True:
		start = a_str.find(sub, start)
		if start == -1:
			return
		yield start
		start += len(sub)

def SieveOfEratosthenes(n, isPrime):
	isPrime[0] = isPrime[1] = False
	for i in range(2, n):
		isPrime[i] = True
	p = 2
	while p * p <= n:
		if isPrime[p] == True:
			i = p * p
			while i <= n:
				isPrime[i] = False
				i += p
		p += 1
	return isPrime

def dijkstra(edges, f, t):
	g = defaultdict(list)
	for (l, r, c) in edges:
		g[l].append((c, r))
	(q, seen, mins) = ([(0, f, ())], set(), {f: 0})
	while q:
		(cost, v1, path) = heappop(q)
		if v1 not in seen:
			seen.add(v1)
			path = (v1, path)
			if v1 == t:
				return (cost, path)
			for (c, v2) in g.get(v1, ()):
				if v2 in seen:
					continue
				prev = mins.get(v2, None)
				next = cost + c
				if prev is None or next < prev:
					mins[v2] = next
					heappush(q, (next, v2, path))
	return float('inf')

def binsearch(a, l, r, x):
	while l <= r:
		mid = l + (r - 1) // 2
		if a[mid]:
			return mid
		elif a[mid] > x:
			l = mid - 1
		else:
			r = mid + 1
	return -1

def readTree(n):
	adj = [set() for _ in range(n)]
	for _ in range(n - 1):
		(u, v) = map(int, input().split())
		adj[u - 1].add(v - 1)
		adj[v - 1].add(u - 1)
	return adj

def treeOrderByDepth(n, adj, root=0):
	parent = [-2] + [-1] * (n - 1)
	ordered = []
	q = deque()
	q.append(root)
	depth = [0] * n
	while q:
		c = q.popleft()
		ordered.append(c)
		for a in adj[c]:
			if parent[a] == -1:
				parent[a] = c
				depth[a] = depth[c] + 1
				q.append(a)
	return (ordered, parent, depth)
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 _ in range(ii()):
	string = si()
	pat = ['123', '132', '213', '231', '312', '321']
	print(len(findSubString(string, pat[0])))


t = int(input())
for _ in range(t):
	s = input()
	a = -1
	b = -1
	c = -1
	mn = 10 ** 9
	for i in range(len(s)):
		if s[i] == '1':
			a = i
		elif s[i] == '2':
			b = i
		else:
			c = i
		if a != -1 and b != -1 and (c != -1):
			mn = min(mn, max(a, b, c) - min(a, b, c) + 1)
	if mn == 10 ** 9:
		print(0)
	else:
		print(mn)


import os, sys
from io import BytesIO, IOBase
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))
try:
	(sys.stdin, sys.stdout) = (open('in.txt', 'r'), open('out.txt', 'w'))
except:
	pass
ii1 = lambda : int(sys.stdin.readline().strip())
is1 = lambda : sys.stdin.readline().strip()
iia = lambda : list(map(int, sys.stdin.readline().strip().split()))
isa = lambda : sys.stdin.readline().strip().split()
mod = int(1000000000.0 + 7)
from collections import *
from math import *
from collections import deque as dq
for _ in range(ii1()):
	s = is1()
	dic = defaultdict(int)
	j = 0
	ans = inf
	n = len(s)
	for i in range(n):
		dic[s[i]] += 1
		if len(dic) == 3:
			ans = min(ans, i - j)
			while len(dic) > 2:
				dic[s[j]] -= 1
				ans = min(ans, i - j)
				if dic[s[j]] == 0:
					del dic[s[j]]
				j += 1
	print(0 if ans == inf else ans + 1)


TT = int(input())
for _ in range(TT):
	s = input()
	one = two = three = None
	import math
	ans = math.inf
	for i in range(len(s)):
		if s[i] == '1':
			one = i
		if s[i] == '2':
			two = i
		if s[i] == '3':
			three = i
		if one != None and two != None and (three != None):
			ll = max(one, two, three) - min(one, two, three) + 1
			ans = min(ans, ll)
	if ans == math.inf:
		print(0)
	else:
		print(ans)


a = int(input())
for i in range(a):
	n = input()
	st = 0
	ed = 0
	chk = [0, 0, 0, 0]
	chk[int(n[0])] += 1
	total = len(n) + 4
	while ed < len(n):
		while chk[3] == 0 or chk[1] == 0 or chk[2] == 0:
			ed += 1
			if ed < len(n):
				chk[int(n[ed])] += 1
			else:
				break
		if ed >= len(n):
			break
		while chk[int(n[st])] > 1:
			chk[int(n[st])] -= 1
			st += 1
		if chk[3] + chk[1] + chk[2] < total:
			total = chk[3] + chk[1] + chk[2]
			if total == 3:
				break
		chk[int(n[st])] -= 1
		st += 1
	if total == len(n) + 4:
		print(0)
	else:
		print(total)


for _ in range(int(input())):
	str1 = list(input())
	l1 = []
	l2 = []
	for i in range(len(str1) - 1):
		if str1[i] == str1[i + 1]:
			l2.append(str1[i])
		else:
			l2.append(str1[i])
			l1.append(l2[:])
			l2.clear()
	l2.append(str1[-1])
	l1.append(l2)
	if len(l1) >= 3:
		k = 0
		min_ = 200000
		for i in range(1, len(l1) - 1):
			if l1[i + 1][0] != l1[i - 1][0]:
				k = 1
				shit = len(l1[i]) + 2
				if shit < min_:
					min_ = shit
		if k == 0:
			print(0)
		else:
			print(min_)
	else:
		print(0)


t = int(input())
while t:
	t += -1
	s = input()
	(c1, c2, c3) = (-1, -1, -1)
	ans = 9999999999
	for i in range(len(s)):
		if s[i] == '1':
			c1 = i
		elif s[i] == '2':
			c2 = i
		else:
			c3 = i
		if c1 != -1 and c2 != -1 and (c3 != -1):
			ans = min(ans, max(c1, c2, c3) - min(c1, c2, c3) + 1)
	if c1 == -1 or c2 == -1 or c3 == -1:
		print(0)
	else:
		print(ans)


import math
import collections
from sys import stdin, stdout, setrecursionlimit
import bisect as bs
t = int(stdin.readline())
for _ in range(t):
	s = input()
	d = {}
	l = [(s[0], 0)]
	for i in range(len(s) - 1):
		d[s[i]] = True
		if s[i] != s[i + 1]:
			l.append((s[i + 1], i + 1))
	d[s[len(s) - 1]] = True
	if len(d) < 3:
		print(0)
	else:
		ans = 10 ** 9 + 1
		for j in range(0, len(l) - 2):
			if l[j][0] != l[j + 1][0] and l[j][0] != l[j + 2][0] and (l[j + 2][0] != l[j + 1][0]):
				tmp = l[j + 2][1] - (l[j + 1][1] - 1) + 1
				if tmp < ans:
					ans = tmp
				else:
					continue
		print(ans)


t = int(input())
for _ in range(t):
	s = input()
	x = {'1': 0, '2': 0, '3': 0}
	x[s[0]] += 1
	count = 1
	total = 1
	startIndex = 0
	result = 1000000000
	for i in range(1, len(s)):
		x[s[i]] += 1
		if s[i] == s[startIndex]:
			total += 1
			for j in range(startIndex, i):
				if x[s[j]] <= 1:
					startIndex = j
					break
				else:
					total -= 1
					x[s[j]] -= 1
					startIndex += 1
		else:
			if x[s[i]] == 1 and count < 3:
				count += 1
			total += 1
		if count == 3:
			result = min(result, total)
	if count == 3:
		print(result)
	else:
		print(0)


t = int(input())
for i in range(t):
	s = input()
	(a, k) = ([s.find('1'), s.find('2'), s.find('3')], len(s) + 1)
	for i in range(len(s)):
		a[int(s[i]) - 1] = i
		k = min(max(a) - min(a) + 1, k)
	if k == len(s) + 1 or min(a) == -1:
		print(0)
	else:
		print(k)


t = int(input())
for tc in range(t):
	s = input()
	n = len(s)
	one = -1
	two = -1
	three = -1
	i = 0
	ans = n + 1
	for i in range(n):
		if int(s[i]) == 1:
			one = i
		if int(s[i]) == 2:
			two = i
		if int(s[i]) == 3:
			three = i
		if min(one, two, three) >= 0:
			ans = min(ans, i - min(one, two, three) + 1)
	if ans <= n:
		print(ans)
	else:
		print('0')


from collections import defaultdict

def smallest(s1, s2):
	if len(s1) <= 2 or '1' not in s1 or '2' not in s1 or ('3' not in s1):
		return 0
	assert s2 != ''
	d = defaultdict(int)
	nneg = [0]

	def incr(c):
		d[c] += 1
		if d[c] == 0:
			nneg[0] -= 1

	def decr(c):
		if d[c] == 0:
			nneg[0] += 1
		d[c] -= 1
	for c in s2:
		decr(c)
	minlen = len(s1) + 1
	j = 0
	for i in range(len(s1)):
		while nneg[0] > 0:
			if j >= len(s1):
				return minlen
			incr(s1[j])
			j += 1
		minlen = min(minlen, j - i)
		decr(s1[i])
	return minlen
t = int(input())
while t:
	t -= 1
	s = input()
	print(smallest(s, '123'))


from collections import defaultdict

def main():
	for _ in range(int(input())):
		s = list(input())
		flag = 0
		d = defaultdict(lambda : 0)
		mini = 10 ** 9
		for i in range(len(s)):
			d[s[i]] = i
			if len(d) == 3:
				if mini > max(d['1'], d['2'], d['3']) - min(d['1'], d['2'], d['3']):
					mini = max(d['1'], d['2'], d['3']) - min(d['1'], d['2'], d['3'])
		if mini != 10 ** 9:
			print(mini + 1)
		else:
			print(0)
main()


import math
t = int(input())
for tt in range(t):
	s = input().strip()
	pr1 = [0] * (len(s) + 1)
	pr2 = [0] * (len(s) + 1)
	pr3 = [0] * (len(s) + 1)
	for i in range(len(s)):
		if i == 0:
			xx = int(s[i])
			if xx == 1:
				pr1[i] = 1
			elif xx == 2:
				pr2[i] = 1
			elif xx == 3:
				pr3[i] = 1
		else:
			xx = int(s[i])
			if xx == 1:
				pr1[i] = 1 + pr1[i - 1]
				pr2[i] = pr2[i - 1]
				pr3[i] = pr3[i - 1]
			elif xx == 2:
				pr1[i] = pr1[i - 1]
				pr3[i] = pr3[i - 1]
				pr2[i] = 1 + pr2[i - 1]
			else:
				pr1[i] = pr1[i - 1]
				pr2[i] = pr2[i - 1]
				pr3[i] = 1 + pr3[i - 1]
	start = 1
	end = len(s)
	ans = 1000000000.0
	while start <= end:
		mid = start + (end - start) // 2
		flag = False
		for i in range(len(s)):
			if i + mid - 1 < len(s):
				t1 = pr1[i + mid - 1]
				t2 = pr2[i + mid - 1]
				t3 = pr3[i + mid - 1]
				if i != 0:
					t1 -= pr1[i - 1]
					t2 -= pr2[i - 1]
					t3 -= pr3[i - 1]
				if t1 > 0 and t2 > 0 and (t3 > 0):
					flag = True
					break
			else:
				break
		if flag:
			end = mid - 1
			ans = min(ans, mid)
		else:
			start = mid + 1
	if ans == 1000000000.0:
		ans = 0
	print(ans)


from collections import defaultdict

def smallest(s1, s2):
	assert s2 != ''
	d = defaultdict(int)
	nneg = [0]

	def incr(c):
		d[c] += 1
		if d[c] == 0:
			nneg[0] -= 1

	def decr(c):
		if d[c] == 0:
			nneg[0] += 1
		d[c] -= 1
	for c in s2:
		decr(c)
	minlen = len(s1) + 1
	j = 0
	for i in range(len(s1)):
		while nneg[0] > 0:
			if j >= len(s1):
				return minlen
			incr(s1[j])
			j += 1
		minlen = min(minlen, j - i)
		decr(s1[i])
	return minlen
for _ in range(int(input())):
	s = input()
	if len(set(s)) != 3:
		print(0)
		continue
	print(smallest(s, '123'))


def solve():
	s = input()
	n = len(s)
	(last_1, last_2, last_3) = (-1, -1, -1)
	found = False
	minn = 2000000
	for i in range(n):
		if s[i] == '1':
			last_1 = i
			if last_1 != -1 and last_2 != -1 and (last_3 != -1):
				found = True
				mn = min(last_2, last_3)
				ll = i - mn + 1
				minn = min(ll, minn)
		elif s[i] == '2':
			last_2 = i
			if last_1 != -1 and last_2 != -1 and (last_3 != -1):
				found = True
				mn = min(last_1, last_3)
				ll = i - mn + 1
				minn = min(ll, minn)
		elif s[i] == '3':
			last_3 = i
			if last_1 != -1 and last_2 != -1 and (last_3 != -1):
				found = True
				mn = min(last_2, last_1)
				ll = i - mn + 1
				minn = min(ll, minn)
	if found == True:
		print(minn)
	else:
		print(0)
t = int(input())
for i in range(t):
	solve()


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():
	t = inp()
	for _ in range(t):
		a = input()
		res = b_serach(a)
		print(res)
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')
main()


t = int(input())
for _ in range(t):
	n = input()
	c = []
	if '1' not in n or '2' not in n or '3' not in n:
		print(0)
	else:
		e = int(n[0])
		count = 1
		a = [int(n[0])]
		for i in range(len(n)):
			b = int(n[i])
			if b != e:
				if b not in a:
					count += 1
				if count == 2:
					index = i
				a.append(b)
			elif b == e:
				if count == 1:
					a = [b]
				else:
					a = []
					for j in range(index, i + 1):
						a.append(int(n[j]))
					e = int(n[index])
					index = i
			if count == 3:
				c.append(len(a))
				a = []
				for j in range(index, i + 1):
					a.append(int(n[j]))
				e = int(n[index])
				index = i
				count = 2
		print(min(c))


def shortest(arr, size):
	minLength = size + 1
	left = 0
	right = 0
	sets = set()
	arrDict = {}
	set1 = {'1', '2', '3'}
	while right <= size:
		while sets == set1 and minLength != 3:
			minLength = min(minLength, right - left)
			arrDict[arr[left]] -= 1
			if arrDict[arr[left]] == 0:
				sets.remove(arr[left])
			left += 1
		if minLength == 3:
			break
		elif right == size:
			break
		elif arr[right] not in sets:
			sets.add(arr[right])
		arrDict[arr[right]] = 1 + arrDict.get(arr[right], 0)
		right += 1
	print(minLength if minLength != size + 1 else 0)
test = int(input())
for _ in range(test):
	lists = list(input())
	size = len(lists)
	shortest(lists, size)


from sys import stdin, stdout
import math, sys
from itertools import permutations, combinations
from collections import defaultdict, deque, OrderedDict
import bisect as bi
import heapq

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

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

def main():
	try:
		l = list(input())
		q = set()
		d = {}
		l1 = [-1] * 3
		(ans, mi) = (0, 10000000.0)
		for i in range(len(l)):
			if l[i] == '1':
				l1[0] = i
			elif l[i] == '2':
				l1[1] = i
			else:
				l1[2] = i
			if min(l1) != -1:
				ans = min(mi, max(l1) - min(l1) + 1)
				mi = ans
		print(ans)
	except:
		pass
M = 998244353
P = 1000000007
for _ in range(I()):
	main()


for _ in range(int(input())):
	s = input()
	(a, b, c) = (-1, -1, -1)
	ans = 10000000
	for i in range(len(s)):
		k = int(s[i]) - 1
		if k == 0:
			a = i
		if k == 1:
			b = i
		if k == 2:
			c = i
		if a != -1 and b != -1 and (c != -1):
			ans = min(ans, max(a, b, c) - min(a, b, c) + 1)
	if ans == 10000000:
		print(0)
	else:
		print(ans)


from math import inf
for i in range(int(input())):
	x = [int(X) for X in list(input())]
	n = len(x)
	on = -1
	tw = -1
	th = -1
	ma = inf
	for j in range(n):
		if x[j] == 1:
			on = j
		elif x[j] == 2:
			tw = j
		else:
			th = j
		if on != -1 and tw != -1 and (th != -1):
			ma = min(ma, max(on, tw, th) - min(on, tw, th))
	if ma == inf:
		print(0)
	else:
		print(ma + 1)


def countChar(d):
	for ch in d.values():
		if ch == 0:
			return False
	return True
for i in range(int(input())):
	arr = input()
	n = len(arr)
	f = 0
	l = 0
	c = 0
	d = {'1': 0, '2': 0, '3': 0}
	x = n + 1
	while f <= l and l < n:
		if f == c:
			char = arr[l]
			d[char] += 1
		else:
			c = f
		if countChar(d):
			if l - f + 1 < x:
				x = l - f + 1
			start_ch = arr[f]
			if d[start_ch] >= 2:
				d[start_ch] -= 1
				f += 1
			else:
				l += 1
		else:
			l += 1
	if x <= n:
		print(x)
	else:
		print(0)


import math
import sys
input = sys.stdin.readline
for _ in range(int(input())):
	s = input().strip()
	if len(set(s)) < 3:
		print(0)
		continue
	i = 0
	res = 205000
	while True:
		while i + 1 < len(s) and s[i] == s[i + 1]:
			i += 1
		ibeg = i
		i += 1
		while i + 1 < len(s) and s[i] == s[i + 1]:
			i += 1
		iend = i + 1
		if iend >= len(s):
			break
		if s[ibeg] != s[iend]:
			res = min(res, iend - ibeg + 1)
		i = iend - 1
	print(res)


from sys import stdin, stdout, setrecursionlimit
from math import ceil
input = stdin.readline
for _ in range(int(input())):
	s = input()
	if '1' not in s or '2' not in s or '3' not in s:
		print(0)
		continue
	i1 = -1
	mn = 99999999
	for i in range(len(s) - 2):
		if s[i] != s[i + 1]:
			if i1 != -1 and s[i1] != s[i + 1]:
				mn = min(mn, i + 2 - i1)
				i1 = i
			else:
				i1 = i
	print(mn)


t = int(input())
for _ in range(t):
	s = input()
	n = len(s)
	(one, two, three) = (-1, -1, -1)
	low = n + 1
	for i in range(n):
		if s[i] == '1' and i > one:
			one = i
		elif s[i] == '2' and i > two:
			two = i
		elif s[i] == '3' and i > three:
			three = i
		if one >= 0 and two >= 0 and (three >= 0):
			low = min(low, max(abs(one - two) + 1, abs(one - three) + 1, abs(two - three) + 1))
	if low == n + 1:
		print(0)
	else:
		print(low)


for _ in range(int(input())):
	s = input()
	i1 = None
	i2 = None
	i3 = None
	n = len(s)
	min1 = n + 1
	nk = 0
	for i in range(0, n):
		if s[i] == '1':
			i1 = i
		elif s[i] == '2':
			i2 = i
		else:
			i3 = i
		if i1 != None and i2 != None and (i3 != None):
			nd = max([i1, i2, i3]) - min([i1, i2, i3])
			nd = nd + 1
			if min1 > nd:
				min1 = nd
				nk = 1
	if nk == 0:
		print(0)
	else:
		print(min1)


t = int(input())
for _ in range(t):
	s = input()
	s = list(s)
	n = len(s)
	(a, b, c) = (-1, -1, -1)
	ans = 200001
	if '1' not in s or '2' not in s or '3' not in s:
		print('0')
	else:
		for i in range(n):
			if s[i] == '1':
				a = i
			elif s[i] == '2':
				b = i
			else:
				c = i
			if a != -1 and b != -1 and (c != -1):
				p = min(a, b, c)
				q = max(a, b, c)
				ans = min(ans, q - p + 1)
		print(ans)


from sys import stdin
t = int(stdin.readline())
for _ in range(t):
	arr = stdin.readline().rstrip()
	idx1 = None
	idx2 = None
	idx3 = None
	bestRes = 10000000000.0
	for i in range(len(arr)):
		char = arr[i]
		if char == '1':
			idx1 = i
		elif char == '2':
			idx2 = i
		else:
			idx3 = i
		if idx1 is not None and idx2 is not None and (idx3 is not None):
			result = max(idx1, idx2, idx3) - min(idx1, idx2, idx3) + 1
			if result < bestRes:
				bestRes = result
	if bestRes == 10000000000.0:
		print(0)
	else:
		print(bestRes)


for _ in range(int(input())):
	l = input()
	ans = []
	(c1, c2, c3) = (-1, -1, -1)
	lth = 0
	for i in range(len(l)):
		if l[i] == '1':
			c1 = i
		elif l[i] == '2':
			c2 = i
		else:
			c3 = i
		if c1 != -1 and c2 != -1 and (c3 != -1):
			mn = min(c1, c2, c3)
			mx = max(c1, c2, c3)
			if c1 == mn:
				c1 = -1
			elif c2 == mn:
				c2 = -1
			else:
				c3 = -1
			lth = mx - mn
			ans.append(lth)
	if len(ans) == 0:
		print(0)
	else:
		print(min(ans) + 1)


for _ in range(int(input())):
	s = input()
	b = []
	for i in range(len(s) - 1):
		if s[i] != s[i + 1]:
			b.append(i)
	ans = float('inf')
	for i in range(1, len(b)):
		if s[b[i - 1]] != s[b[i] + 1]:
			ans = min(b[i] + 2 - b[i - 1], ans)
	if ans == float('inf'):
		print(0)
		continue
	print(ans)


import bisect
t = int(input())
for _ in range(t):
	s = input()
	l = len(s)
	pos1 = []
	pos2 = []
	pos3 = []
	for i in range(l):
		if s[i] == '1':
			pos1.append(i)
		elif s[i] == '2':
			pos2.append(i)
		elif s[i] == '3':
			pos3.append(i)
	l1 = len(pos1)
	l2 = len(pos2)
	l3 = len(pos3)
	ans = 10 ** 18
	for p1 in pos1:
		p2 = bisect.bisect_left(pos2, p1)
		if p2 == l2:
			continue
		p2 = pos2[p2]
		p3 = bisect.bisect_left(pos3, p2)
		if p3 == l3:
			continue
		p3 = pos3[p3]
		ans = min(ans, p3 - p1 + 1)
	for p1 in pos1:
		p2 = bisect.bisect_left(pos3, p1)
		if p2 == l3:
			continue
		p2 = pos3[p2]
		p3 = bisect.bisect_left(pos2, p2)
		if p3 == l2:
			continue
		p3 = pos2[p3]
		ans = min(ans, p3 - p1 + 1)
	for p1 in pos2:
		p2 = bisect.bisect_left(pos1, p1)
		if p2 == l1:
			continue
		p2 = pos1[p2]
		p3 = bisect.bisect_left(pos3, p2)
		if p3 == l3:
			continue
		p3 = pos3[p3]
		ans = min(ans, p3 - p1 + 1)
	for p1 in pos2:
		p2 = bisect.bisect_left(pos3, p1)
		if p2 == l3:
			continue
		p2 = pos3[p2]
		p3 = bisect.bisect_left(pos1, p2)
		if p3 == l1:
			continue
		p3 = pos1[p3]
		ans = min(ans, p3 - p1 + 1)
	for p1 in pos3:
		p2 = bisect.bisect_left(pos1, p1)
		if p2 == l1:
			continue
		p2 = pos1[p2]
		p3 = bisect.bisect_left(pos2, p2)
		if p3 == l2:
			continue
		p3 = pos2[p3]
		ans = min(ans, p3 - p1 + 1)
	for p1 in pos3:
		p2 = bisect.bisect_left(pos2, p1)
		if p2 == l2:
			continue
		p2 = pos2[p2]
		p3 = bisect.bisect_left(pos1, p2)
		if p3 == l1:
			continue
		p3 = pos1[p3]
		ans = min(ans, p3 - p1 + 1)
	if ans == 10 ** 18:
		print(0)
	else:
		print(ans)


def main():
	t = int(input())
	for _ in range(t):
		s = input()
		n = len(s)
		c = [0 for i in range(n)]
		d = [0 for i in range(n)]
		e = [0 for i in range(n)]
		for j in range(n):
			if s[j] == '1':
				c[j] = 1
			elif s[j] == '2':
				d[j] = 1
			else:
				e[j] = 1
		c1 = [0] + c
		d1 = [0] + d
		e1 = [0] + e
		for i in range(n):
			c1[i + 1] += c1[i]
			d1[i + 1] += d1[i]
			e1[i + 1] += e1[i]
		if sum(c) == 0 or sum(d) == 0 or sum(e) == 0:
			print(0)
		else:
			ans = float('inf')
			max_l = 0
			for i in range(n):
				if c1[n] - c1[i] > 0 and d1[n] - d1[i] > 0 and (e1[n] - e1[i] > 0):
					l = max(max_l, i)
					r = min(n, l + ans)
					while r - l > 1:
						m = (r + l) // 2
						if c1[m] - c1[i] > 0 and d1[m] - d1[i] > 0 and (e1[m] - e1[i] > 0):
							r = m
						else:
							l = m
					max_l = max(max_l, l)
					ans = min(ans, r - i)
			print(ans)
main()


import sys
input = sys.stdin.readline
n = int(input())
for i in range(n):
	o = [9999999, 99999999, 999999999]
	s = input()
	best = 99999999
	for c in range(len(s)):
		if s[c] == '1':
			o[0] = c
		if s[c] == '2':
			o[1] = c
		if s[c] == '3':
			o[2] = c
		if max(o) - min(o) < best:
			best = max(o) - min(o)
	if best > 999999:
		print(0)
	else:
		print(best + 1)


def ter(j):
	one = -1
	two = -1
	three = -1
	sum = 0
	for i in range(len(j)):
		if j[i] == '1':
			one = i
		elif j[i] == '2':
			two = i
		else:
			three = i
		if one != -1 and two != -1 and (three != -1):
			a = max([one, two, three]) - min([one, two, three]) + 1
			if a < sum or sum == 0:
				sum = a
	return sum
t = int(input())
l = []
for i in range(t):
	s = input()
	l.append(s)
for j in l:
	print(ter(j))


testcases = int(input())
for testcase in range(testcases):
	strs = input()
	one = []
	two = []
	three = []
	for (index, i) in enumerate(strs):
		if i == '1':
			one.append(index)
		elif i == '3':
			three.append(index)
		elif i == '2':
			two.append(index)
	len_one = len(one)
	len_two = len(two)
	len_three = len(three)
	if len_three == 0 or len_two == 0 or len_one == 0:
		print(0)
		continue
	indexone = 0
	indextwo = 0
	indexthree = 0
	minslength = len(strs)
	while indexone < len_one and indextwo < len_two and (indexthree < len_three):
		getmin = min(one[indexone], two[indextwo], three[indexthree])
		getmax = max(one[indexone], two[indextwo], three[indexthree])
		curdiff = getmax - getmin + 1
		if curdiff < minslength:
			minslength = curdiff
		if one[indexone] < two[indextwo] and one[indexone] < three[indexthree]:
			indexone += 1
			continue
		if two[indextwo] < one[indexone] and two[indextwo] < three[indexthree]:
			indextwo += 1
			continue
		if three[indexthree] < two[indextwo] and three[indexthree] < one[indexone]:
			indexthree += 1
			continue
	print(minslength)


def solve(s):
	(i, j) = (0, 0)
	n = len(s)
	cnt = n + 1
	while i < n:
		while i + 1 < n and s[i] == s[i + 1]:
			i += 1
		j = i + 1
		while j + 1 < n and s[j] == s[j + 1]:
			j += 1
		if j + 1 >= n:
			break
		if s[i] != s[j + 1]:
			cnt = min(cnt, j - i + 2)
		i = j
	cnt = cnt if cnt != n + 1 else 0
	return cnt

def main():
	inp = lambda : [int(x) for x in input().split()]
	tc = int(input())
	for _ in range(tc):
		s = input()
		print(solve(s))
main()


n = int(input())
for _ in range(n):
	s = input()
	i = j = k = float('inf')
	current = 0
	dist = float('inf')
	for l in range(len(s)):
		if s[l] == '1':
			i = l
		elif s[l] == '2':
			j = l
		else:
			k = l
		if max(i, j, k) - min(i, j, k) + 1 < dist:
			dist = max(i, j, k) - min(i, j, k) + 1
	if dist != float('inf'):
		print(dist)
	else:
		print(0)


import sys, math
from itertools import permutations, combinations
from collections import defaultdict, Counter, deque
from math import factorial
from bisect import bisect_left
sys.setrecursionlimit(10 ** 7)
enu = enumerate
MOD = 10 ** 9 + 7

def input():
	return sys.stdin.readline()[:-1]
pl = lambda x: print(*x, sep='\n')

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

def solve():
	S = input()
	N = len(S)
	left = 0
	right = 0
	ott = defaultdict(int)
	res = N
	ott[S[right]] += 1
	while left < N:
		while right < N - 1 and (not chk(ott)):
			right += 1
			ott[S[right]] += 1
		if left == 0 and right == N - 1 and (not chk(ott)):
			print(0)
			return
		if chk(ott):
			val = right - left + 1
			if val < res:
				res = val
		if left == right:
			right += 1
			if right >= N:
				break
			ott[S[right]] += 1
		ott[S[left]] -= 1
		left += 1
	print(res)
	return
T = int(input())
for t in range(T):
	solve()


def solve():
	s = input()
	a = [0] * 4
	l = 0
	r = 0
	ans = 999999
	l = 0
	while r < len(s):
		a[int(s[r])] += 1
		while a[int(s[l])] > 1:
			a[int(s[l])] -= 1
			l += 1
		if a[1] != 0 and a[3] != 0 and (a[2] != 0):
			ans = min(ans, r - l + 1)
		r += 1
	if ans == 999999:
		return 0
	return ans
for _ in range(int(input())):
	print(solve())


import math
t = int(input())
for _ in range(t):
	s = input()
	n = len(s)
	f = [False] * 3
	tt = [True] * 3
	ans = 10000000000
	a = list(s)
	if s.count('1') == 0 or s.count('2') == 0 or s.count('3') == 0:
		print(0)
	else:
		ind = s.index('1')
		i = ind
		m = 1
		while i < n:
			if i < n:
				if s[i] == '2':
					f[1] = True
					m += 1
					i += 1
				elif s[i] == '3':
					f[2] = True
					m += 1
					i += 1
				elif s[i] == '1':
					f = [True, False, False]
					m = 1
					i += 1
			if f == tt:
				if m < ans:
					if m < 3:
						m = 3
					ans = m
				f = [True, False, False]
				while i < n:
					if s[i] == '1':
						break
					else:
						i += 1
		ind = s.index('2')
		i = ind
		m = 1
		f = [False] * 3
		while i < n:
			if i < n:
				if s[i] == '1':
					f[0] = True
					m += 1
					i += 1
				elif s[i] == '3':
					f[2] = True
					m += 1
					i += 1
				elif s[i] == '2':
					f = [False, True, False]
					m = 1
					i += 1
			if f == tt:
				if m < ans:
					if m < 3:
						m = 3
					ans = m
				f = [False, True, False]
				while i < n:
					if s[i] == '2':
						break
					else:
						i += 1
		ind = s.index('3')
		i = ind
		f = [False] * 3
		m = 1
		while i < n:
			if i < n:
				if s[i] == '2':
					f[1] = True
					m += 1
					i += 1
				elif s[i] == '1':
					f[0] = True
					m += 1
					i += 1
				elif s[i] == '3':
					f = [False, False, True]
					m = 1
					i += 1
			if f == tt:
				if m < ans:
					if m < 3:
						m = 3
					ans = m
				f = [False, False, True]
				while i < n:
					if s[i] == '3':
						break
					else:
						i += 1
		print(ans)


import math
for _ in range(int(input())):
	s = input()
	n = len(s) + 1
	arr = [[-1, -1, -1] for i in range(n)]
	for i in range(n - 2, -1, -1):
		for j in range(3):
			if s[i] == str(j + 1):
				arr[i][j] = i
			else:
				arr[i][j] = arr[i + 1][j]
	mi = 10 ** 12

	def check(x, y):
		for k in range(3):
			if k + 1 not in [x, y]:
				return k
	if min(arr[0]) == -1:
		print(0)
	else:
		for i in range(n - 2):
			if s[i] != s[i + 1]:
				ind = check(int(s[i]), int(s[i + 1]))
				if arr[i + 1][ind] != -1:
					mi = min(mi, arr[i + 1][ind] - i + 1)
		print(mi)


from sys import stdin, stdout
import math
from itertools import permutations, combinations
from collections import defaultdict
from bisect import bisect_left
from bisect import bisect_right

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

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

def I():
	return int(stdin.readline())
P = 1000000007
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]

def main():
	for t in range(I()):
		s = input()
		print(len(findSubString(s, '123')))
main()


n = int(input())
for _ in range(n):
	string = input()
	min_length = float('inf')
	cur_score = 1
	cur_length = 1
	cur = [string[0]]
	start = 0
	end = 0
	for i in range(1, len(string)):
		if string[i] not in cur:
			cur.append(string[i])
			cur_score += 1
		elif string[i] != string[i - 1]:
			start = i - 1
		elif cur_score == 1:
			start = i
		end = i
		cur_length = end - start + 1
		if cur_score == 3:
			min_length = min(min_length, cur_length)
			if min_length == 3:
				break
			cur = [string[i - 1], string[i]]
			start = i - 1
			cur_score = 2
			cur_length = 2
	if min_length == float('inf'):
		print(0)
	else:
		print(min_length)


import math

def dtb(n):
	return bin(n).replace('0b', '')

def btd(n):
	return int(n, 2)
t = int(input())
for k in range(t):
	s = input()
	n = len(s)
	i = 0
	a = set()
	while i < n - 2:
		count = 0
		if s[i] == s[i + 1]:
			i += 1
		else:
			count += 2
			j = i + 2
			while j < n:
				if s[j] == s[i]:
					break
				elif s[j] == s[i + 1]:
					j += 1
					count += 1
				else:
					count += 1
					a.add(count)
					break
			i += 1
	if len(a) == 0:
		print(0)
	else:
		print(min(a))


for _ in range(int(input())):
	a = list(input())
	b = [-1] * 3
	m = 0
	for i in range(len(a)):
		b[int(a[i]) - 1] = i
		if b[0] > -1 and b[1] > -1 and (b[2] > -1):
			if m == 0:
				m = max(b) - min(b) + 1
			else:
				m = min(m, max(b) - min(b) + 1)
	print(m)


t = int(input())
for i in range(t):
	s = input()
	m = 0
	l = [-1] * 3
	for j in range(len(s)):
		l[int(s[j]) - 1] = j
		if l[0] > -1 and l[1] > -1 and (l[2] > -1):
			if m == 0:
				m = max(l) - min(l) + 1
			else:
				m = min(m, max(l) - min(l) + 1)
	print(m)


t = int(input())
for i in range(t):
	s = input()
	s = list(s)
	for i in range(len(s)):
		s[i] = int(s[i])
	j = k = 0
	n = len(s)
	d = {}
	c = 1
	max = float('inf')
	while j < n:
		if c == 1:
			if s[j] not in d:
				d[s[j]] = 1
			else:
				d[s[j]] = d[s[j]] + 1
		l = len(d)
		if l < 3:
			j = j + 1
		if l == 3:
			l1 = list(d.values())
			m = sum(l1)
			c = 0
			if max > m:
				max = m
			if d.get(s[k]) > 1:
				d[s[k]] = d[s[k]] - 1
			elif d.get(s[k]) == 1:
				d.pop(s[k])
			if len(d) < 3:
				j = j + 1
				c = 1
			k = k + 1
	if max == float('inf'):
		max = 0
	print(max)


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


T = int(input())
for t in range(T):
	s = input()
	if '1' not in s or '2' not in s or '3' not in s:
		print(0)
	else:
		n = len(s)
		ans = n
		interest_point = []
		for i in range(1, n):
			if s[i] != s[i - 1]:
				interest_point.append(i)
		m = len(interest_point)
		for i in range(m - 1):
			if s[interest_point[i] - 1] != s[interest_point[i + 1]]:
				ans = min(ans, interest_point[i + 1] - interest_point[i] + 2)
		print(ans)


t = int(input())
INT_MAX = 10 ** 10
while t:
	s = str(input())
	mi = INT_MAX
	n = len(s)
	mp = {'1': -INT_MAX, '2': -INT_MAX, '3': -INT_MAX}
	for i in range(n):
		mp[s[i]] = i
		temp = min(list(mp.values()))
		mi = min(mi, i - temp + 1)
	if mi >= INT_MAX:
		print(0)
	else:
		print(mi)
	t -= 1


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))


t = int(input())
for _ in range(t):
	s = list(map(int, input()))
	n = len(s)
	left = 0
	right = 0
	curlist = s[0]
	c = [0, 0, 0, 0]
	c[s[0]] = 1
	minlen = n + 1
	while True:
		if c[1] == 0 or c[2] == 0 or c[3] == 0:
			if right == n - 1:
				break
			else:
				right += 1
				c[s[right]] += 1
		else:
			if right - left + 1 < minlen:
				minlen = right - left + 1
			c[s[left]] -= 1
			left += 1
	if minlen == n + 1:
		print(0)
	else:
		print(minlen)


from collections import defaultdict

def small(s):
	n = len(s)
	dist = len(set([x for x in s]))
	curr = defaultdict(lambda : 0)
	count = 0
	min_len = n
	start = 0
	for j in range(n):
		curr[s[j]] += 1
		if curr[s[j]] == 1:
			count += 1
		if count == dist:
			while curr[s[start]] > 1:
				if curr[s[start]] > 1:
					curr[s[start]] -= 1
				start += 1
			len_window = j - start + 1
			if min_len > len_window:
				min_len = len_window
				start_index = start
	return min_len
for _ in range(int(input())):
	s = list(input())
	if '1' in s and '2' in s and ('3' in s):
		if '123' in str(s) or '132' in str(s) or '213' in str(s) or ('231' in str(s)) or ('312' in str(s)) or ('321' in str(s)):
			print(3)
		else:
			mn = small(''.join(s))
			print(mn)
	else:
		print(0)


t = int(input())
for i in range(t):
	S = input()
	l = len(S)
	a = -1
	b = -1
	c = -1
	s = 999999999
	for j in range(l):
		if S[j] == '1':
			a = j
		elif S[j] == '2':
			b = j
		elif S[j] == '3':
			c = j
		if a >= 0 and b >= 0 and (c >= 0):
			x = max(a, b, c)
			y = min(a, b, c)
			z = x - y + 1
			if z < s:
				s = z
	if s == 999999999:
		print('0')
	else:
		print(s)


from collections import defaultdict as dd
from collections import deque
import bisect
import heapq

def ri():
	return int(input())

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

def solve():
	s = input()
	last = {i: -1 for i in '123'}
	others = {'1': '23', '2': '13', '3': '12'}
	shortest = 10 ** 10
	for (i, c) in enumerate(s):
		works = True
		furthest = 0
		for other in others[c]:
			if last[other] == -1:
				works = False
			else:
				furthest = max(furthest, i - last[other])
		if works:
			shortest = min(shortest, furthest)
		last[c] = i
	if shortest <= len(s):
		print(shortest + 1)
	else:
		print(0)
mode = 'T'
if mode == 'T':
	t = ri()
	for i in range(t):
		solve()
else:
	solve()


t = int(input())
for _ in range(t):
	s = input()
	l = 0
	r = 0
	ans = 10 ** 9
	cnt = [0] * 3
	while r < len(s):
		while r < len(s) and cnt[0] * cnt[1] * cnt[2] == 0:
			cnt[int(s[r]) - 1] += 1
			r += 1
		if r == len(s) and cnt[0] * cnt[1] * cnt[2] == 0:
			break
		while cnt[0] * cnt[1] * cnt[2] != 0:
			cnt[int(s[l]) - 1] -= 1
			l += 1
		ans = min(ans, r - l + 1)
	print(ans if ans < 10 ** 9 else 0)


from sys import stdin
import math
t = int(stdin.readline())
for _ in range(t):
	s = input()
	r = 0
	unique = {}
	ans = float('inf')
	while r < len(s):
		if len(unique) == 3:
			start_key = min('1', '2', '3', key=lambda x: unique[x])
			ans = min(ans, r - unique[start_key])
			del unique[start_key]
			start_key = min('1', '2', '3', key=lambda x: unique.get(x, float('inf')))
			r = unique[start_key]
			unique = {}
		else:
			unique[s[r]] = r
			r += 1
	if r == len(s) and len(unique) == 3:
		start_key = min('1', '2', '3', key=lambda x: unique[x])
		ans = min(ans, r - unique[start_key])
	elif ans == float('inf'):
		ans = 0
	print(ans)


t = int(input())
for ti in range(t):
	s = input().strip()
	recInd = {}
	ans = 1000000.0
	for (i, c) in enumerate(s):
		recInd[c] = i
		if len(recInd) == 3:
			length = max(recInd.values()) - min(recInd.values()) + 1
			if length < ans:
				ans = length
	print(ans if ans != 1000000.0 else 0)


for i in range(int(input())):
	s = input()
	mini = 200001
	if len(set(s)) != 3:
		print(0)
	else:
		l = [0]
		for i in range(1, len(s)):
			if s[i] != s[i - 1]:
				l.append(i)
		for i in range(len(l) - 2):
			if set(s[l[i]:l[i + 2] + 1]) == {'1', '2', '3'}:
				if l[i + 2] - l[i + 1] + 2 < mini:
					mini = l[i + 2] - l[i + 1] + 2
		print(mini)


import sys
import collections
input = sys.stdin.readline

def main():
	t = int(input())
	for _ in range(t):
		S = input().strip()
		c = collections.Counter()
		r = 0
		ans = float('inf')
		for l in range(len(S)):
			while r < len(S) and (c['1'] == 0 or c['2'] == 0 or c['3'] == 0):
				c[S[r]] += 1
				r += 1
			if c['1'] > 0 and c['2'] > 0 and (c['3'] > 0):
				ans = min(ans, r - l)
			c[S[l]] -= 1
		if ans == float('inf'):
			print(0)
		else:
			print(ans)
main()


import math, string, itertools, fractions, heapq, collections, re, array, bisect, sys, copy, functools
sys.setrecursionlimit(10 ** 7)
inf = 10 ** 20
eps = 1.0 / 10 ** 10
mod = 10 ** 9 + 7
mod2 = 998244353
dd = [(-1, 0), (0, 1), (1, 0), (0, -1)]
ddn = [(-1, 0), (-1, 1), (0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1)]

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

def LLI():
	return [list(map(int, l.split())) for l in sys.stdin.readlines()]

def LI_():
	return [int(x) - 1 for x in sys.stdin.readline().split()]

def LF():
	return [float(x) for x in sys.stdin.readline().split()]

def LS():
	return sys.stdin.readline().split()

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

def F():
	return float(sys.stdin.readline())

def S():
	return input()

def pf(s):
	return print(s, flush=True)

def pe(s):
	return print(str(s), file=sys.stderr)

def JA(a, sep):
	return sep.join(map(str, a))

def JAA(a, s, t):
	return s.join((t.join(map(str, b)) for b in a))

def IF(c, t, f):
	return t if c else f

def main():
	t = I()
	rr = []
	for _ in range(t):
		a = [int(c) - 1 for c in S()]
		l = len(a)
		t = [0] * 3
		i = 0
		while i < l:
			t[a[i]] += 1
			i += 1
			if all(t):
				break
		if not all(t):
			rr.append(0)
			continue
		j = 0
		while j < l:
			c = a[j]
			if t[c] < 2:
				break
			t[c] -= 1
			j += 1
		r = i - j
		while i < l:
			t[a[i]] += 1
			i += 1
			while j < l:
				c = a[j]
				if t[c] < 2:
					break
				t[c] -= 1
				j += 1
			if r > i - j:
				r = i - j
		rr.append(r)
	return JA(rr, '\n')
print(main())


import math
el = int(input())
for i in range(el):
	st = input()
	one = 0
	two = 0
	three = 0
	ch1 = 0
	ch2 = 0
	ch3 = 0
	count = 0
	for i in range(len(st)):
		if ch1 != 0 and ch2 != 0 and (ch3 != 0):
			if st[i] == '1':
				one = i
			elif st[i] == '2':
				two = i
			else:
				three = i
			temp = max(one, two, three) - min(one, two, three)
			if temp < count:
				count = temp
		else:
			if st[i] == '1':
				one = i
				if ch1 == 0:
					ch1 = 1
			elif st[i] == '2':
				two = i
				if ch2 == 0:
					ch2 = 1
			else:
				three = i
				if ch3 == 0:
					ch3 = 1
			if ch1 != 0 and ch2 != 0 and (ch3 != 0):
				count = max(one, two, three) - min(one, two, three)
	if ch1 != 0 and ch2 != 0 and (ch3 != 0):
		print(count + 1)
	else:
		print(0)


from math import inf
for _ in range(int(input())):
	ternary_str = input()
	if ternary_str.count('1') == 0 or ternary_str.count('2') == 0 or ternary_str.count('3') == 0:
		print(0)
	else:
		(index_1, index_2, index_3, size) = (-1, -1, -1, inf)
		for i in range(len(ternary_str)):
			if ternary_str[i] == '1':
				index_1 = i
			elif ternary_str[i] == '2':
				index_2 = i
			elif ternary_str[i] == '3':
				index_3 = i
			if index_1 != -1 and index_2 != -1 and (index_3 != -1):
				size = min(size, max(index_1, index_2, index_3) - min(index_1, index_2, index_3) + 1)
		print(size)


t = int(input())
for _ in range(t):
	s = input().rstrip()
	n = len(s)
	l = []
	pprev = s[0]
	idxppr = 0
	prev = idxpr = -1
	for i in range(n):
		if s[i] != pprev:
			prev = s[i]
			idxpr = i
			break
	j = idxpr
	for i in range(n):
		if s[i] == prev:
			idxpr += 1
			prev = s[idxpr]
		elif s[i] == pprev:
			idxppr = idxpr
			idxpr = i
			pprev = s[idxppr]
			prev = s[idxpr]
		else:
			l.append(i - idxppr + 1)
			idxppr = idxpr
			idxpr = i
			pprev = s[idxppr]
			prev = s[idxpr]
	if len(l) > 0:
		print(min(l))
	else:
		print(0)


ans = []
for _ in range(int(input())):
	s = input()
	min_length = len(s)
	if len(set(s)) < 3:
		ans.append(0)
		continue
	inside = []
	length = 0
	last = s[0]
	for i in range(len(s)):
		if i == 0:
			inside.append(s[i])
			length = 1
		elif s[i] == last:
			if len(inside) == 1:
				continue
			else:
				length += 1
		else:
			if s[i] not in inside:
				inside.append(s[i])
				length += 1
			else:
				length = 2
			if len(inside) == 3:
				min_length = min(min_length, length)
				inside = [last, s[i]]
				length = 2
		last = s[i]
	ans.append(min_length)
print('\n'.join(map(str, (x for x in ans))))


import math
from collections import Counter

def listToString(l):
	s = ''
	for c in l:
		s += c
	return s

def solution():
	n = int(input())
	for i in range(n):
		s = input()
		l = len(s)
		f = 0
		b = 0
		count = {}
		cMin = 0
		while b < l:
			if s[b] not in count:
				count[s[b]] = 1
			else:
				count[s[b]] = count[s[b]] + 1
			while len(count) == 3:
				curr = 0
				for k in count:
					curr += count[k]
				if cMin == 0:
					cMin = curr
				else:
					cMin = min(curr, cMin)
				e = s[f]
				if count[e] == 1:
					del count[e]
				else:
					count[e] -= 1
				f += 1
			b += 1
		print(cMin)
solution()


from math import gcd, ceil
from collections import defaultdict as dd

def lcm(a, b):
	return a * b // gcd(a, b)

def inin():
	return int(input())

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

def ar(element, size):
	return [element for i in range(size)]

def digitsum(num):
	su = 0
	while num:
		su += num % 10
		num //= 10
	return su

def yes():
	print('YES')

def no():
	print('NO')
Testcase = inin()
for _ in range(Testcase):
	arr = list(input())
	n = len(arr)
	last1 = float('inf')
	last2 = float('inf')
	last3 = float('inf')
	ans = float('inf')
	for i in range(n):
		if arr[i] == '1':
			last1 = i
		if arr[i] == '2':
			last2 = i
		if arr[i] == '3':
			last3 = i
		ans = min(ans, max(last1, last2, last3) - min(last1, last2, last3) + 1)
	if ans == float('inf'):
		print(0)
	else:
		print(ans)


import math
for _ in range(int(input())):
	word = input()
	s = {'1', '2', '3'}
	ans = math.inf
	if len(word) < 3:
		print(0)
		continue
	else:
		(index, current) = (1, word[1])
		for i in range(2, len(word)):
			if word[i] != current:
				if s == {current, word[index - 1], word[i]}:
					ans = min(ans, i - index)
				current = word[i]
				index = i
	if ans == math.inf:
		if len(set(word)) != 3:
			print(0)
		else:
			print(198919891989)
	else:
		print(ans + 2)


big = 10 ** 10
t = int(input())
for case in range(t):
	s = list(map(lambda x: int(x) - 1, input()))
	k = len(s)
	best = big
	last = [-big] * 3
	for pos in range(k):
		last[s[pos]] = pos
		best = min(best, pos - min(last) + 1)
	print(best if best < big else 0)


from collections import Counter

def solve_2():
	t = int(input())
	for i in range(t):
		st = input()
		left = 0
		right = -1
		cc = Counter(st)
		if len(cc.keys()) < 3:
			print(0)
		else:
			ans = float('inf')
			balance = {'1': 0, '2': 0, '3': 0}
			while True:
				if balance['1'] < 1 or balance['2'] < 1 or balance['3'] < 1:
					right += 1
					balance[st[right]] += 1
				else:
					ans = min(ans, right - left + 1)
					balance[st[left]] -= 1
					left += 1
				if right == len(st) - 1 and (balance['1'] < 1 or balance['2'] < 1 or balance['3'] < 1):
					break
			print(ans)
solve_2()


import re
for _ in range(int(input())):
	s = input()
	l = [-1] * 3
	r = 1000000000.0
	for x in range(len(s)):
		l[int(s[x]) - 1] = x
		if min(l) != -1:
			x = max(l) - min(l)
			if x < r:
				r = x
	print(r + 1 if r != 1000000000.0 else 0)


t = int(input())
for i in range(t):
	s = input()
	a = -1
	b = -1
	c = -1
	ans = len(s)
	cur = []
	if s.count('1') == 0 or s.count('2') == 0 or s.count('3') == 0:
		print(0)
	else:
		for i in range(len(s)):
			if s[i] == '1':
				a = i
			elif s[i] == '2':
				b = i
			else:
				c = i
			cur = [a, b, c]
			if min(cur) >= 0:
				ans = min(ans, max(cur) - min(cur) + 1)
		print(ans)


import os
import sys
from io import BytesIO, IOBase
from collections import Counter

def main():
	for t in range(int(input())):
		s = input()
		n = len(s)

		def fun(x):
			d = dict()
			for i in range(x):
				if s[i] in d:
					d[s[i]] += 1
				else:
					d[s[i]] = 1
			ct = 0
			for key in d:
				if d[key] > 0:
					ct += 1
			if ct == 3:
				return True
			for i in range(1, n - x + 1):
				d[s[i - 1]] -= 1
				if s[i + x - 1] in d:
					d[s[i + x - 1]] += 1
				else:
					d[s[i + x - 1]] = 1
				ct = 0
				for key in d:
					if d[key] > 0:
						ct += 1
				if ct == 3:
					return True
			return False
		lf = 1
		rt = n
		ans = 1000000000000.0
		while lf <= rt:
			mid = lf + (rt - lf) // 2
			if fun(mid):
				rt = mid - 1
				ans = min(ans, mid)
			else:
				lf = mid + 1
		if ans == 1000000000000.0:
			print(0)
		else:
			print(ans)
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))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


import math
t = int(input())
for i in range(t):
	s = list(input())
	f = -1
	se = -2
	th = -3
	mx = len(s) + 1
	for q in range(len(s)):
		if s[q] == '1':
			f = q
		elif s[q] == '2':
			se = q
		else:
			th = q
		if f >= 0 and se >= 0 and (th >= 0):
			r = max(f, se, th)
			t = min(f, se, th)
			mx = min(r - t + 1, mx)
	if mx == len(s) + 1:
		print(0)
	else:
		print(mx)


t = int(input())
for q in range(t):
	s = input()
	if '1' not in s or '2' not in s or '3' not in s or (len(s) < 3):
		print(0)
	else:
		flag1 = -1
		flag2 = -1
		flag3 = -1
		maximo = len(s) + 1
		for k in range(len(s)):
			if s[k] == '1':
				flag1 = k
				if flag1 != -1 and flag2 != -1 and (flag3 != -1):
					m = max(flag1, max(flag2, flag3)) - min(flag1, min(flag2, flag3)) + 1
					if m < maximo:
						maximo = m
			elif s[k] == '2':
				flag2 = k
				if flag1 != -1 and flag2 != -1 and (flag3 != -1):
					m = max(flag1, max(flag2, flag3)) - min(flag1, min(flag2, flag3)) + 1
					if m < maximo:
						maximo = m
			else:
				flag3 = k
				if flag1 != -1 and flag2 != -1 and (flag3 != -1):
					m = max(flag1, max(flag2, flag3)) - min(flag1, min(flag2, flag3)) + 1
					if m < maximo:
						maximo = m
		print(maximo)


import sys, math
I = sys.stdin.readline
ans = ''

def isvalid(k):
	arr = {'1': 0, '2': 0, '3': 0}
	for i in range(k - 1):
		arr[s[i]] += 1
	for i in range(k - 1, len(s)):
		arr[s[i]] += 1
		if arr['1'] > 0 and arr['2'] > 0 and (arr['3'] > 0):
			return True
		arr[s[i - k + 1]] -= 1
	return False
for _ in range(int(I())):
	s = I().strip()
	l = 3
	r = len(s)
	res = math.inf
	while l <= r:
		mid = l + (r - l) // 2
		if isvalid(mid):
			res = mid
			r = mid - 1
		else:
			l = mid + 1
	if res == math.inf:
		ans += '0\n'
	else:
		ans += str(res) + '\n'
print(ans)


t = int(input())
for _ in range(t):
	s = input()
	ids = []
	acc = []
	curr = 1
	for i in range(1, len(s)):
		if s[i] == s[i - 1]:
			pass
		else:
			ids.append(s[i - 1])
			acc.append(curr)
			curr = 0
		curr += 1
	ids.append(s[-1])
	acc.append(curr)
	ans = float('inf')
	for i in range(1, len(ids) - 1):
		if len(list(set([ids[i - 1], ids[i], ids[i + 1]]))) == 3:
			ans = min(ans, acc[i] + 2)
	if ans == float('inf'):
		print(0)
	else:
		print(ans)


t = int(input())
for _ in range(t):
	s = input()
	if '1' not in s or '2' not in s or '3' not in s:
		print(0)
	else:
		i = 0
		a = []
		ans = float('inf')
		while i < len(s):
			x = s[i]
			c = 0
			while i < len(s) and s[i] == x:
				i += 1
				c += 1
			a.append((x, c))
		for i in range(len(a) - 2):
			if a[i][0] == '1':
				if a[i + 1][0] == '2':
					if a[i + 2][0] == '3':
						ans = min(ans, a[i + 1][1] + 2)
				elif a[i + 1][0] == '3':
					if a[i + 2][0] == '2':
						ans = min(ans, a[i + 1][1] + 2)
			elif a[i][0] == '2':
				if a[i + 1][0] == '1':
					if a[i + 2][0] == '3':
						ans = min(ans, a[i + 1][1] + 2)
				elif a[i + 1][0] == '3':
					if a[i + 2][0] == '1':
						ans = min(ans, a[i + 1][1] + 2)
			elif a[i][0] == '3':
				if a[i + 1][0] == '1':
					if a[i + 2][0] == '2':
						ans = min(ans, a[i + 1][1] + 2)
				elif a[i + 1][0] == '2':
					if a[i + 2][0] == '1':
						ans = min(ans, a[i + 1][1] + 2)
		print(ans)


import math
t = int(input())
for _ in range(t):
	arr = list(map(int, input().strip()))
	countArr = []
	numArr = []
	count = 1
	d = {}
	min_val = 1000000000
	s = set(arr)
	if len(s) < 3:
		print('0')
	else:
		for i in range(len(arr) - 1):
			if arr[i] == arr[i + 1]:
				count += 1
			else:
				countArr.append(count)
				numArr.append(arr[i])
				count = 1
		if arr[len(arr) - 2] == arr[len(arr) - 1]:
			countArr.append(count)
			numArr.append(arr[len(arr) - 2])
		if arr[len(arr) - 1] != arr[len(arr) - 2]:
			numArr.append(arr[len(arr) - 1])
			countArr.append(1)
		if len(numArr) < 3:
			print('0')
		else:
			for i in range(2):
				if numArr[i] not in d:
					d[numArr[i]] = 1
			for i in range(2, len(numArr)):
				if numArr[i] not in d:
					d[numArr[i]] = 1
				else:
					d[numArr[i]] += 1
				if len(d) == 3:
					min_val = min(min_val, 2 + countArr[i - 1])
				if d[numArr[i - 2]] > 1:
					d[numArr[i - 2]] -= 1
				else:
					d.pop(numArr[i - 2])
			print(min_val)


for _ in range(int(input())):
	s = input()
	if len(set(s)) < 3:
		print(0)
	else:
		n = len(s)
		ans = n
		(a, b, c) = (0, 1, 2)
		while s[b] == s[b - 1]:
			(a, b, c) = (a + 1, b + 1, c + 1)
		while c < n:
			while c < n and s[c] == s[c - 1]:
				(b, c) = (b + 1, c + 1)
			if c < n and s[a] != s[b] != s[c] != s[a]:
				ans = min(c - a + 1, ans)
			(a, b, c) = (b, c, c + 1)
		print(ans)


t = int(input())
while t != 0:
	t -= 1
	s = input()
	l = [-1] * 3
	m = 3000000
	for i in range(len(s)):
		l[int(s[i]) - 1] = i
		if min(l) != -1:
			m = min(m, max(l) - min(l) + 1)
	if m == 3000000:
		print(0)
	else:
		print(m)


import math
m = 1000000007

def fact(n):
	ans = 1
	for i in range(1, n + 1):
		ans = ans % m * (i % m) % m
	return ans

def power_2(n):
	ans = 1
	for i in range(n):
		ans = ans % m * 2 % m
	return ans
for z in range(int(input())):
	s = input()
	n = len(s)
	(i, j) = (0, 1)
	a = []
	while j < n:
		if s[i] != s[j]:
			while j < n - 1 and s[j] == s[j + 1]:
				j += 1
			if j < n - 1 and s[i] != s[j + 1]:
				a.append(j + 2 - i)
			i = j
			j = j + 1
		else:
			i += 1
			j += 1
	if len(a) == 0:
		print(0)
	else:
		print(min(a))


import sys

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

def sieve(n):
	a = [1] * n
	for i in range(2, n):
		if a[i]:
			for j in range(i * i, n, i):
				a[j] = 0
	return a
for __ in range(int(input())):
	arr = input()
	n = len(arr)
	poss = []
	i = 0
	while i < n - 1 and arr[i] == arr[i + 1]:
		i += 1
	i += 1
	ans = n + 1
	while i < n - 1:
		prev = arr[i - 1]
		c = 1
		while i < n - 1 and arr[i] == arr[i + 1]:
			i += 1
			c += 1
		i += 1
		if i > n - 1:
			break
		nex = arr[i]
		if prev != nex:
			ans = min(ans, c + 2)
	print(ans) if ans < n + 1 else print(0)


t = int(input())
while t:
	t -= 1
	s = input()
	(l1, l2, l3) = (-1, -1, -1)
	mx_len = len(s)
	for x in range(len(s)):
		if s[x] == '1':
			l1 = x
		if s[x] == '2':
			l2 = x
		if s[x] == '3':
			l3 = x
		if l1 > -1 and l2 > -1 and (l3 > -1):
			mx_len = min(max(l1, l2, l3) - min(l1, l2, l3), mx_len)
	if l1 < 0 or l2 < 0 or l3 < 0:
		print('0')
	else:
		print(mx_len + 1)


tests = int(input())

def isGood(freq):
	if freq[1] > 0 and freq[2] > 0 and (freq[3] > 0):
		return True
	return False
while tests > 0:
	s = input()
	if len(s) < 3:
		print(0)
	else:
		minLen = len(s) + 1
		freq = [0, 0, 0, 0]
		(l, r) = (0, 0)
		freq[int(s[l])] += 1
		for i in range(1, len(s)):
			freq[int(s[i])] += 1
			if isGood(freq):
				minLen = min(minLen, i - l + 1)
				while isGood(freq) and l < i:
					minLen = min(minLen, i - l + 1)
					freq[int(s[l])] -= 1
					l += 1
		if minLen > len(s):
			print(0)
		else:
			print(minLen)
	tests -= 1


test = int(input())
for t in range(test):
	st = input()
	n = len(st)
	l = 0
	r = 0
	dic = {1: 0, 2: 0, 3: 0}
	m = n + 1
	while r <= n:
		if dic[1] >= 1 and dic[2] >= 1 and (dic[3] >= 1):
			if r - l < m:
				m = r - l
			dic[int(st[l])] -= 1
			l += 1
		elif r < n:
			dic[int(st[r])] += 1
			r += 1
		else:
			r += 1
	if m != n + 1:
		print(m)
	else:
		print(0)


from bisect import bisect_left as bl
from bisect import bisect_right as br
from heapq import heappush, heappop
import math
from collections import *
from functools import reduce, cmp_to_key
import sys
input = sys.stdin.readline
M = mod = 998244353

def factors(n):
	return sorted(set(reduce(list.__add__, ([i, n // i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0))))

def inv_mod(n):
	return pow(n, mod - 2, mod)

def li():
	return [int(i) for i in input().rstrip('\n').split()]

def st():
	return input().rstrip('\n')

def val():
	return int(input().rstrip('\n'))

def li2():
	return [i for i in input().rstrip('\n')]

def li3():
	return [int(i) for i in input().rstrip('\n')]
for _ in range(val()):
	i = j = 0
	s = li3()
	n = len(s)
	a = b = c = 0
	ans = float('inf')
	while j < len(s):
		if s[j] == 1:
			a += 1
		elif s[j] == 2:
			b += 1
		else:
			c += 1
		if a and b and c:
			while i < j:
				if s[i] == 1:
					if a > 1:
						a -= 1
					else:
						break
				elif s[i] == 2:
					if b > 1:
						b -= 1
					else:
						break
				elif c > 1:
					c -= 1
				else:
					break
				i += 1
			ans = min(ans, j - i + 1)
		j += 1
	if ans != float('inf'):
		print(ans)
	else:
		print(0)


t = int(input())
for _ in range(t):
	s = input()
	l = [-1, -1, -1]
	ans = []
	for i in range(len(s)):
		if s[i] == '1':
			l[0] = i
			if l.count(-1) == 0:
				ans.append(i - min(l))
				for i in range(3):
					if l[i] == min(l):
						l[i] = -1
		elif s[i] == '2':
			l[1] = i
			if l.count(-1) == 0:
				ans.append(i - min(l))
				for i in range(3):
					if l[i] == min(l):
						l[i] = -1
		elif s[i] == '3':
			l[2] = i
			if l.count(-1) == 0:
				ans.append(i - min(l))
				for i in range(3):
					if l[i] == min(l):
						l[i] = -1
	try:
		print(min(ans) + 1)
	except:
		print(0)


from collections import Counter
from collections import defaultdict

def minWindow(s, t):
	left = right = 0
	minLen = float('inf')
	tCounter = Counter(t)
	sCounter = defaultdict(int)
	count = 0
	res = ''
	while right < len(s):
		sCounter[s[right]] += 1
		if s[right] in tCounter and sCounter[s[right]] <= tCounter[s[right]]:
			count += 1
		while left <= right and count == len(t):
			if minLen > right - left + 1:
				minLen = right - left + 1
				res = s[left:right + 1]
			sCounter[s[left]] -= 1
			if s[left] in tCounter and sCounter[s[left]] < tCounter[s[left]]:
				count -= 1
			left += 1
		right += 1
	return res
for _ in range(int(input())):
	s = input()
	t = '123'
	rst = minWindow(s, t)
	print(len(rst))


from collections import defaultdict
for _ in range(int(input())):
	str = input()
	if str.find('1') == -1 or str.find('2') == -1 or str.find('3') == -1:
		print(0)
		continue
	n = len(str)
	dc = 3
	cc = defaultdict(lambda : 0)
	count = 0
	start = 0
	min_len = 200001
	for j in range(n):
		cc[str[j]] += 1
		if cc[str[j]] == 1:
			count += 1
		if count == dc:
			while cc[str[start]] > 1:
				if cc[str[start]] > 1:
					cc[str[start]] -= 1
				start += 1
			len_window = j - start + 1
			if min_len > len_window:
				min_len = len_window
				si = start
	print(min_len)


INF = 1000000000.0
for t in range(int(input())):
	s = input()
	curr_len = 0
	curr_char = s[0]
	segs = []
	for c in s:
		if c == curr_char:
			curr_len += 1
		else:
			segs.append((curr_char, curr_len))
			curr_char = c
			curr_len = 1
	segs.append((curr_char, curr_len))
	ans = INF
	for i in range(len(segs) - 2):
		if sorted([segs[i + k][0] for k in range(3)]) == ['1', '2', '3']:
			ans = min(ans, 1 + segs[i + 1][1] + 1)
	print(0 if ans == INF else ans)


from sys import stdin
for _ in range(int(stdin.readline())):
	s = stdin.readline()
	a = [0] * 3
	b = 0
	ans = len(s) + 1
	for (i, si) in enumerate(s):
		if si == '1':
			a[0] += 1
		if si == '2':
			a[1] += 1
		if si == '3':
			a[2] += 1
		while all(a):
			ans = min(ans, i + 1 - b)
			if b == i:
				break
			bi = s[b]
			if bi == '1':
				a[0] -= 1
			if bi == '2':
				a[1] -= 1
			if bi == '3':
				a[2] -= 1
			b += 1
	if ans == len(s) + 1:
		ans = 0
	print(ans)


t = int(input())
for i in range(t):
	s = input()
	left = 0
	right = 0
	dic = {'1': 0, '2': 0, '3': 0}
	n = len(s)
	dic[s[0]] += 1
	ans = float('inf')
	while left < n and right < n:
		if dic['1'] and dic['2'] and dic['3']:
			ans = min(sum(dic.values()), ans)
			dic[s[left]] -= 1
			left += 1
		else:
			right += 1
			if right == n:
				break
			dic[s[right]] += 1
	print(ans if ans != float('inf') else 0)


from collections import Counter
t = int(input())
while t:
	t -= 1
	s = input()
	n = len(s)
	d = Counter(s)
	z = {i: [-1, -1, -1] for i in range(n)}
	if len(d) < 3:
		print(0)
		continue
	for i in range(n - 1, -1, -1):
		if s[i] == '1':
			if i == n - 1:
				z[i] = [i, -1, -1]
				continue
			else:
				z[i] = [i, z[i + 1][1], z[i + 1][2]]
				continue
		if s[i] == '2':
			if i == n - 1:
				z[i] = [-1, i, -1]
				continue
			else:
				z[i] = [z[i + 1][0], i, z[i + 1][2]]
				continue
		if s[i] == '3':
			if i == n - 1:
				z[i] = [-1, -1, i]
				continue
			else:
				z[i] = [z[i + 1][0], z[i + 1][1], i]
				continue
	l = [n for i in range(n)]
	for i in range(n):
		l[i] = max(z[i]) - min(z[i]) + 1
	print(min(l))


for _ in range(int(input())):
	s = input()
	l = [[s[0], 0, 0]]
	ans = []
	length = len(s)
	i = 1
	while i < len(s):
		while i < len(s) and s[i] == s[i - 1]:
			i += 1
		l[-1][2] = i - 1
		if i < len(s):
			l.append([s[i], i, i])
			i += 1
	for i in range(0, len(l) - 3 + 1):
		j = l[i:i + 3]
		if ['1', '2', '3'] == sorted([j[0][0], j[1][0], j[2][0]]):
			ans.append(j[2][1] - j[0][2] + 1)
	if len(ans) == 0:
		print(0)
	else:
		print(min(ans))


for z in range(int(input())):
	s = input()
	n = len(s)
	i = 0
	j = 0
	ca = 0
	cb = 0
	cc = 0
	minl = 10000000
	while i < n:
		if s[i] == '1':
			ca += 1
		if s[i] == '2':
			cb += 1
		if s[i] == '3':
			cc += 1
		while (ca > 0 and cb > 0 and (cc > 0)) and j < n:
			length = i - j + 1
			if minl > length:
				minl = length
			if s[j] == '1':
				ca -= 1
			if s[j] == '2':
				cb -= 1
			if s[j] == '3':
				cc -= 1
			j += 1
		i += 1
	if minl == 10000000:
		print(0)
	else:
		print(minl)


for _ in range(int(input())):
	s = list(input())
	a = [0] * 3
	ans = float('inf')
	for i in range(len(s)):
		a[int(s[i]) - 1] = i + 1
		if all(a):
			(t1, t2) = (max(a), min(a))
			ans = min(ans, t1 - t2 + 1)
	print(ans if ans != float('inf') else 0)


t = int(input())
for _ in range(t):
	s = input()
	x = y = z = -len(s) - 1
	ans = len(s)
	if '1' in s and '2' in s and ('3' in s):
		for i in range(len(s)):
			if s[i] == '1':
				x = i
			if s[i] == '2':
				y = i
			if s[i] == '3':
				z = i
			ans = min(ans, i - min(x, y, z) + 1)
		print(ans)
	else:
		print(0)


t = int(input())
for i in range(t):
	s = input()
	cnt = [-1, -1, -1]
	i = 0
	n = len(s)
	ans = float('inf')
	while i < n:
		cnt[int(s[i]) - 1] = i
		if cnt[0] != -1 and cnt[1] != -1 and (cnt[2] != -1):
			ans = min(ans, max(cnt) - min(cnt) + 1)
		i += 1
	if ans == float('inf'):
		print(0)
	else:
		print(ans)


import sys
input = sys.stdin.readline
t = int(input())
out = []
for _ in range(t):
	s = input().strip()
	n = len(s)
	best = n + 1
	last1 = -best
	last2 = -best
	last3 = -best
	for i in range(n):
		c = s[i]
		if c == '1':
			last1 = i
		elif c == '2':
			last2 = i
		else:
			last3 = i
		curr = i - min(last1, last2, last3) + 1
		best = min(best, curr)
	if best <= n:
		out.append(best)
	else:
		out.append(0)
print(*out, sep='\n')


import sys
q = int(input())
for i in range(q):
	a = sys.stdin.readline()
	b = [9999999] * len(a)
	last1 = -9999999
	last2 = -9999999
	last3 = -9999999
	for i in range(len(a)):
		if a[i] == '1':
			b[i] = i - min(last2, last3)
			last1 = i
		if a[i] == '2':
			b[i] = i - min(last1, last3)
			last2 = i
		if a[i] == '3':
			b[i] = i - min(last2, last1)
			last3 = i
	if last1 == -9999999 or last2 == -9999999 or last3 == -9999999:
		print(0)
	else:
		print(min(b) + 1)


for _ in range(int(input())):
	tekst = input()
	(sta_1, sta_2, sta_3, mini) = (-1, -1, -1, len(tekst))
	for x in range(len(tekst)):
		if tekst[x] == '1':
			sta_1 = x
		elif tekst[x] == '2':
			sta_2 = x
		else:
			sta_3 = x
		if sta_1 != -1 and sta_2 != -1 and (sta_3 != -1):
			mini = min(mini, max(sta_3, sta_2, sta_1) - min(sta_3, sta_2, sta_1) + 1)
	if sta_1 != -1 and sta_2 != -1 and (sta_3 != -1):
		print(mini)
	else:
		print(0)


import sys, math, cmath, time
start_time = time.time()
tt = 0
from collections import defaultdict

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

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

def insr():
	return input().strip()

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

def solve():
	a = insr()
	d = len(set([i for i in a]))
	q = defaultdict(lambda : 0)
	cc = 0
	t = 0
	s = -1
	m = 10000000000000000
	for j in range(len(a)):
		q[a[j]] += 1
		if q[a[j]] == 1:
			cc += 1
		if cc == d:
			while q[a[t]] > 1:
				if q[a[t]] > 1:
					q[a[t]] -= 1
				t += 1
			l = j - t + 1
			if m > l:
				m = l
				s = t
	if len(set(a)) == 3:
		print(len(a[s:s + m]))
	else:
		print(0)

def main():
	if not ONLINE_JUDGE:
		sys.stdin = open('input.txt', 'r')
		sys.stdout = open('output.txt', 'w')
	t = 1
	t = inp()
	for tt in range(t):
		solve()
	if not ONLINE_JUDGE:
		print('Time Elapsed :', time.time() - start_time, 'seconds')
	sys.stdout.close()

def counter(a):
	q = [0] * max(a)
	for i in range(len(a)):
		q[a[i] - 1] = q[a[i] - 1] + 1
	return q

def string_counter(a):
	q = [0] * 26
	for i in range(len(a)):
		q[ord(a[i]) - 97] = q[ord(a[i]) - 97] + 1
	return q
ONLINE_JUDGE = __debug__
if ONLINE_JUDGE:
	input = sys.stdin.readline
main()


no_of_chars = 256

def findSubString(string, pat):
	len1 = len(string)
	len2 = len(pat)
	if len1 < len2:
		return 'NO'
	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 'NO'
	return string[start_index:start_index + min_len]

def solve():
	for _ in range(int(input())):
		string = input()
		pattern = '123'
		ans = findSubString(string, pattern)
		if ans == 'NO':
			print(0)
		else:
			print(len(ans))
solve()


for _ in range(int(input())):
	s = str(input())
	ind = [-1, -1, -1, -1]
	n = len(s)
	ans = float('inf')
	for i in range(n):
		ind[ord(s[i]) - ord('0')] = i
		if ind[1] >= 0 and ind[2] >= 0 and (ind[3] >= 0):
			ans = min(ans, max(ind[1], max(ind[2], ind[3])) - min(ind[1], min(ind[2], ind[3])) + 1)
	if ans == float('inf'):
		print(0)
	else:
		print(ans)


import math
for _ in range(int(input())):
	a = str(input())
	n = len(a)
	i = 1
	s = set()
	b = []
	b.append(a[0])
	b.append(0)
	s.add(a[0])
	while len(s) != 3 and i < n:
		if a[i] == b[0]:
			b[1] = i
		elif len(s) == 1:
			b.append(a[i])
			b.append(i)
			s.add(a[i])
		elif a[i] == b[2]:
			b[3] = i
		else:
			b.append(a[i])
			b.append(i)
			s.add(a[i])
		i += 1
	if len(s) == 3:
		ans = b[5] - min(b[1], b[3])
		res = ans
		while i < n:
			if a[i] == b[0]:
				b[1] = i
			elif a[i] == b[2]:
				b[3] = i
			else:
				b[5] = i
			ans = max(b[1], b[3], b[5]) - min(b[1], b[3], b[5])
			if res > ans:
				res = ans
			i += 1
		print(res + 1)
	else:
		print(0)


t = int(input())
while t:
	s = input()
	w = [-len(s), -len(s), -len(s)]
	ans = 1000000
	for i in range(len(s)):
		w[int(s[i]) - 1] = i
		ans = min(ans, max(w) - min(w) + 1)
	if ans > len(s):
		print(0)
	else:
		print(ans)
	t = t - 1


import sys
input = lambda : sys.stdin.readline().rstrip()
t = int(input())
x = [list((int(i) for i in input())) for j in range(t)]
for i in range(t):
	ans = pow(10, 9)
	v = [0, 0, 0]
	r = 1
	l = 0
	for j in range(len(x[i])):
		v[x[i][j] - 1] += 1
		r += 1
		if min(v) >= 1:
			ans = min(r - l, ans)
			while min(v) >= 1:
				v[x[i][l] - 1] -= 1
				l += 1
				ans = min(r - l, ans)
	if ans == pow(10, 9):
		print(0)
	else:
		print(ans)


import sys
input = sys.stdin.readline

def ceil(x):
	if x != int(x):
		x = int(x) + 1
	return x

def factorial(x, m):
	val = 1
	while x > 0:
		val = val * x % m
		x -= 1
	return val

def swaparr(arr, a, b):
	temp = arr[a]
	arr[a] = arr[b]
	arr[b] = temp

def gcd(a, b):
	if b == 0:
		return a
	return gcd(b, a % b)

def nCr(n, k):
	if k > n - k:
		k = n - k
	res = 1
	for i in range(k):
		res = res * (n - i)
		res = res / (i + 1)
	return int(res)

def upper_bound(a, x, lo=0, hi=None):
	if hi == None:
		hi = len(a)
	while lo < hi:
		mid = (lo + hi) // 2
		if a[mid] < x:
			lo = mid + 1
		else:
			hi = mid
	return lo

def primefs(n):
	primes = {}
	while n % 2 == 0 and n > 0:
		primes[2] = primes.get(2, 0) + 1
		n = n // 2
	for i in range(3, int(n ** 0.5) + 2, 2):
		while n % i == 0 and n > 0:
			primes[i] = primes.get(i, 0) + 1
			n = n // i
	if n > 2:
		primes[n] = primes.get(n, 0) + 1
	return primes

def power(x, y, p):
	res = 1
	x = x % p
	if x == 0:
		return 0
	while y > 0:
		if y & 1 == 1:
			res = res * x % p
		y = y >> 1
		x = x * x % p
	return res

def swap(a, b):
	temp = a
	a = b
	b = temp
	return (a, b)

def find(x, link):
	p = x
	while p != link[p]:
		p = link[p]
	while x != p:
		nex = link[x]
		link[x] = p
		x = nex
	return p

def union(x, y, link, size):
	x = find(x, link)
	y = find(y, link)
	if size[x] < size[y]:
		(x, y) = swap(x, y)
	if x != y:
		size[x] += size[y]
		link[y] = x

def sieve(n):
	prime = [True for i in range(n + 1)]
	p = 2
	while p * p <= n:
		if prime[p] == True:
			for i in range(p * p, n + 1, p):
				prime[i] = False
		p += 1
	return prime
MAXN = int(100000.0 + 5)

def spf_sieve():
	spf[1] = 1
	for i in range(2, MAXN):
		spf[i] = i
	for i in range(4, MAXN, 2):
		spf[i] = 2
	for i in range(3, ceil(MAXN ** 0.5), 2):
		if spf[i] == i:
			for j in range(i * i, MAXN, i):
				if spf[j] == j:
					spf[j] = i

def factoriazation(x):
	ret = {}
	while x != 1:
		ret[spf[x]] = ret.get(spf[x], 0) + 1
		x = x // spf[x]
	return ret

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

def float_array():
	return list(map(float, input().strip().split()))

def str_array():
	return input().strip().split()
MOD = int(1000000000.0) + 7
CMOD = 998244353
INF = float('inf')
NINF = -float('inf')
from itertools import permutations
import math

def solve():
	a = list(input())
	if a[-1] == '\n':
		a.pop()
	block = []
	prev = 0
	i = 0
	comp = a[0]
	while i < len(a):
		while i < len(a) and a[i] == comp:
			i += 1
		block.append((prev, i))
		if i == len(a):
			break
		prev = i
		comp = a[prev]
	ans = INF
	for x in block:
		if x[1] < len(a) and x[0] > 0 and (a[x[0] - 1] != a[x[1]]):
			val = x[1] - x[0] + 2
			ans = min(ans, val)
	if ans == INF:
		print(0)
		return
	print(ans)
for _ in range(int(input())):
	solve()


for _ in range(int(input())):
	s = input()
	rng = []
	(start, cur) = (0, s[0])
	for i in range(1, len(s)):
		if cur != s[i]:
			rng.append((start, i))
			start = i
			cur = s[i]
	ans = 200001
	for (l, r) in rng:
		if 0 < l and r < len(s):
			if s[l - 1] != s[r]:
				ans = min(ans, r - l + 2)
	print(ans if ans != 200001 else 0)


for _ in range(int(input())):
	s = input()
	cnt = 0
	ans = len(s) + 1
	m = {'1': -1, '2': -1, '3': -1}
	for i in range(len(s)):
		if m[s[i]] == -1:
			cnt = cnt + 1
		m[s[i]] = i
		if cnt == 3:
			ans = min(ans, max(m.values()) - min(m.values()) + 1)
			m[min(m.items(), key=lambda x: x[1])[0]] = -1
			cnt = cnt - 1
	if ans == len(s) + 1:
		ans = 0
	print(ans)


t = int(input())
while t:
	t -= 1
	s = input()
	val1 = s[0]
	val2 = ''
	d = {}
	st = 0
	mid = 0
	ans = 1000000000
	for i in range(len(s)):
		if s[i] not in d.keys():
			d[s[i]] = 1
		else:
			d[s[i]] += 1
		if len(d.keys()) == 1 or val1 == s[i]:
			st = i
			val1 = s[i]
		elif len(d.keys()) == 2:
			mid = i
			val2 = s[i]
		elif len(d.keys()) == 3:
			ans = min(ans, i - min(st, mid) + 1)
			d.pop(s[min(st, mid)])
			if st < mid:
				st = mid
				val1 = val2
			mid = i
			val2 = s[i]
	if ans == 1000000000:
		print(0)
	else:
		print(ans)


t = int(input())
for _ in range(t):
	e = input()
	count = len(e) + 1
	d = [-1, -1, -1]
	for i in range(len(e)):
		d[int(e[i]) - 1] = i
		if -1 not in d:
			if count > max(d) - min(d) + 1:
				count = max(d) - min(d) + 1
	if len(e) + 1 == count:
		print(0)
	else:
		print(count)


from math import *
from random import *
for t in range(int(input())):
	s = input()
	n = len(s)
	p1 = -100000000000
	p2 = p1
	p3 = p1
	otv = 999999999
	for i in range(n):
		if s[i] == '1':
			otv = min(otv, i - min(p2, p3) + 1)
			p1 = i
		if s[i] == '2':
			otv = min(otv, i - min(p1, p3) + 1)
			p2 = i
		if s[i] == '3':
			otv = min(otv, i - min(p2, p1) + 1)
			p3 = i
	if otv > len(s):
		print(0)
	else:
		print(otv)


t = int(input())
for _ in range(t):
	s = input()
	l = [0] * 4
	sm = 0
	length = len(s) + 1
	right = 0
	flag = False
	for i in range(len(s)):
		l[int(s[i])] += 1
		if l[1] > 0 and l[2] > 0 and (l[3] > 0):
			flag = True
			length = min(length, i - right + 1)
			while right < i and l[1] > 0 and (l[2] > 0) and (l[3] > 0):
				l[int(s[right])] -= 1
				right += 1
			if right < i:
				length = min(length, i - right + 2)
	if flag == True:
		print(length)
	else:
		print(0)


from collections import defaultdict as dd

def fs(s):
	n = len(s)
	dc = len(set([x for x in s]))
	cc = dd(lambda : 0)
	start = 0
	si = -1
	ml = 1000000
	count = 0
	for j in range(n):
		cc[s[j]] += 1
		if cc[s[j]] == 1:
			count += 1
		if count == dc:
			while cc[s[start]] > 1:
				if cc[s[start]] > 1:
					cc[s[start]] -= 1
				start += 1
			lw = j - start + 1
			if ml > lw:
				ml = lw
				si = start
	return s[si:si + ml]
for _ in range(int(input())):
	s = input()
	a1 = s.count('1')
	a2 = s.count('2')
	a3 = s.count('3')
	if a1 == 0 or a2 == 0 or a3 == 0:
		print(0)
	else:
		print(len(fs(s)))


t = int(input())
for i in range(t):
	a = input()
	n = len(a)
	b = []
	c = [-1, -1, -1]
	for i in range(n):
		if a[i] == '1':
			if c[1] >= 0 and c[2] >= 0:
				b.append(max(i - c[1], i - c[2]))
			c[0] = i
		if a[i] == '2':
			if c[0] >= 0 and c[2] >= 0:
				b.append(max(i - c[0], i - c[2]))
			c[1] = i
		if a[i] == '3':
			if c[0] >= 0 and c[1] >= 0:
				b.append(max(i - c[0], i - c[1]))
			c[2] = i
	if b == []:
		print(0)
	else:
		print(min(b) + 1)


import sys
import bisect
import heapq
from math import *
from collections import Counter as counter
from itertools import combinations as comb
from itertools import permutations as permutate
from bisect import bisect_left as bl
from bisect import bisect_right as br
from bisect import bisect
mod = pow(10, 9) + 7

def inp():
	return sys.stdin.readline().strip()

def out(var):
	sys.stdout.write(str(var))

def lis():
	return list(map(int, inp().split()))

def stringlis():
	return list(map(str, inp().split()))

def sep():
	return map(int, inp().split())

def strsep():
	return map(str, inp().split())

def graph(vertex):
	return [[] for i in range(0, vertex + 1)]

def zerolist(n):
	return [0] * n

def nextline():
	out('\n')

def testcase(t):
	for p in range(t):
		solve()

def printlist(a):
	for p in range(0, len(a)):
		out(str(a[p]) + ' ')

def lcm(a, b):
	return a * b // gcd(a, b)

def solve():
	s = inp()
	a = -1
	b = -1
	c = -1
	ans = 10 ** 9
	for i in range(0, len(s)):
		if s[i] == '1':
			a = i
		if s[i] == '2':
			b = i
		if s[i] == '3':
			c = i
		if a != -1 and b != -1 and (c != -1):
			ans = min(ans, i - min(a, b, c) + 1)
	if ans == 10 ** 9:
		print(0)
	else:
		print(ans)
testcase(int(inp()))


import sys
import heapq
try:
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
except:
	pass
input = sys.stdin.readline
for i in range(int(input())):
	a = input()
	q = -1
	w = -1
	e = -1
	r = 0
	t = len(a)
	for i in range(len(a)):
		if a[i] == '1':
			q = max(q, i)
		if a[i] == '2':
			w = max(w, i)
		if a[i] == '3':
			e = max(e, i)
		if min(q, w, e) >= 0:
			r = 1
			t = min(max(q, w, e) - min(q, w, e) + 1, t)
	if r == 1:
		print(t)
	else:
		print(0)


from collections import defaultdict
MAX_CHARS = 256

def findSubString(str):
	n = len(str)
	count = 0
	start = 0
	min_len = 1000000009
	start_index = -1
	dist_count = len(set([x for x in str]))
	curr_count = defaultdict(lambda : 0)
	for j in range(n):
		curr_count[str[j]] += 1
		if curr_count[str[j]] == 1:
			count += 1
		if count == dist_count:
			while curr_count[str[start]] > 1:
				if curr_count[str[start]] > 1:
					curr_count[str[start]] -= 1
				start += 1
			len_window = j - start + 1
			if min_len > len_window:
				min_len = len_window
				start_index = start
	return str[start_index:start_index + min_len]
t = int(input())
for _ in range(t):
	s = input()
	l = findSubString(s)
	if len(l) == 1 or len(l) == 2:
		print(0)
	else:
		print(len(l))


import sys
sys.setrecursionlimit(10 ** 8)
INF = float('inf')
mod = 10 ** 9 + 7
eps = 10 ** (-7)
input = sys.stdin.readline

def check(cnts):
	return min(cnts) > 0
T = int(input())
ansl = []
for t in range(T):
	ss = list(map(int, list(input()[:-1])))
	L = len(ss)
	r = 0
	cnts = [0, 0, 0]
	ans = INF
	for l in range(L):
		while check(cnts) == False and r < L:
			cnts[ss[r] - 1] += 1
			r += 1
		if check(cnts):
			ans = min(ans, sum(cnts))
		cnts[ss[l] - 1] -= 1
	if ans == INF:
		ansl.append(0)
	else:
		ansl.append(ans)
print('\n'.join(map(str, ansl)))


n = int(input())
t = []
for i in range(n):
	t.append(input())
for a in t:
	m = [a[0]]
	c = 0
	for i in a:
		if ((i != m[m.__len__() - 1] or m.__len__() >= 2) and (m.__contains__(i) or m.__len__() < 2)) and m[0] != i:
			m.append(i)
		elif i != m[m.__len__() - 1] and m.__contains__(i):
			temp = m.pop()
			m.clear()
			m.append(temp)
			m.append(i)
		elif not m.__contains__(i):
			if c == 0 or m.__len__() + 1 < c:
				c = m.__len__() + 1
			temp = m.pop()
			m.clear()
			m.append(temp)
			m.append(i)
	print(c)
	m.clear()


import sys

def func(arr, mid):
	if len(arr) == mid:
		return 1
	for i in range(len(arr) - mid + 1):
		f = 0
		for j in range(3):
			x = pre[j][i + mid - 1] - pre[j][i] + mat[j][i]
			if x > 0:
				f += 1
		if f == 3:
			return 1
	return 0
for _ in range(int(input())):
	arr = list(map(int, input()))
	uni = list(set(arr))
	if len(uni) == 3:
		l = 3
		r = len(arr)
		mat = [[0 for i in range(len(arr))] for i in range(3)]
		pre = [[0 for i in range(len(arr))] for i in range(3)]
		for i in range(len(arr)):
			mat[arr[i] - 1][i] = 1
		pre[arr[0] - 1][0] = 1
		for i in range(1, len(arr)):
			pre[0][i] = pre[0][i - 1] + mat[0][i]
			pre[1][i] = pre[1][i - 1] + mat[1][i]
			pre[2][i] = pre[2][i - 1] + mat[2][i]
		while l < r:
			mid = (l + r) // 2
			v = func(arr, mid)
			if v == 1:
				r = mid
			else:
				l = mid
			if r - l == 1:
				break
		if func(arr, l) == 1:
			print(l)
		else:
			print(r)
	else:
		print(0)


t = int(input())
for _ in [0] * t:
	s = input()
	r = 0
	l = [-1] * 3
	for j in range(len(s)):
		l[int(s[j]) - 1] = j
		if l[0] > -1 and l[1] > -1 and (l[2] > -1):
			if r > 0:
				r = min(r, max(l) - min(l) + 1)
			else:
				r = max(l) - min(l) + 1
	print(r)


from sys import stdin, stdout
import math
from collections import Counter, deque
L = lambda : list(map(int, stdin.readline().strip().split()))
M = lambda : map(int, stdin.readline().strip().split())
I = lambda : int(stdin.readline().strip())
IN = lambda : stdin.readline().strip()
C = lambda : stdin.readline().strip().split()
mod = 1000000007

def s(a):
	print(' '.join(list(map(str, a))))
for _ in range(I()):
	s = IN()
	a = []
	b = []
	c = 1
	n = len(s)
	x = n + 2
	for i in range(1, n):
		if s[i] == s[i - 1]:
			c += 1
		else:
			a.append(c)
			b.append(int(s[i - 1]))
			c = 1
	a.append(c)
	b.append(int(s[n - 1]))
	for i in range(len(a)):
		if i and i != len(a) - 1:
			if b[i - 1] != b[i + 1]:
				x = min(x, a[i] + 2)
	if x == n + 2:
		print(0)
	else:
		print(x)


import math
import time
from collections import defaultdict, deque
from sys import stdin, stdout
from bisect import bisect_left, bisect_right
no_of_chars = 256

def findSubString(string, pat):
	len1 = len(string)
	len2 = len(pat)
	if len1 < len2:
		print('No such window exists')
		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:
		print('No such window exists')
		return ''
	return string[start_index:start_index + min_len]
t = int(stdin.readline())
for _ in range(t):
	s = input()
	c1 = 0
	c2 = 0
	c3 = 0
	for i in s:
		if i == '1':
			c1 += 1
		elif i == '2':
			c2 += 1
		else:
			c3 += 1
	if c1 == 0 or c2 == 0 or c3 == 0:
		print(0)
	else:
		print(len(findSubString(s, '123')))


t = int(input())
inf = float('INF')

def ab(i, j):
	if i == -1:
		return inf
	return j - i + 1
for _ in range(t):
	s = str(input())
	n = len(s)
	d = [int(i) for i in s]
	on = -1
	tw = -1
	th = -1
	ans = inf
	for i in range(n):
		if d[i] == 1:
			on = i
			ans = min(ans, ab(min(tw, th), i))
		elif d[i] == 2:
			tw = i
			ans = min(ans, ab(min(on, th), i))
		else:
			th = i
			ans = min(ans, ab(min(tw, on), i))
	if ans == inf:
		print(0)
	else:
		print(ans)


t = int(input())
while t:
	s = input()
	a = list(s)
	a = [int(i) for i in a]
	d = []
	i = 1
	freq = 1
	while i < len(a):
		if a[i] == a[i - 1]:
			freq += 1
		else:
			d.append([a[i - 1], freq])
			freq = 1
		i += 1
	d.append([a[len(a) - 1], freq])
	min_len = 999999999
	for i in range(1, len(d) - 1):
		if d[i][0] != d[i - 1][0] and d[i + 1][0] != d[i][0] and (d[i + 1][0] != d[i - 1][0]):
			length = d[i][1] + 2
			if length < min_len:
				min_len = length
	if min_len == 999999999:
		print(0)
	else:
		print(min_len)
	t -= 1


import sys
reader = (s.rstrip() for s in sys.stdin)
input = reader.__next__

def gift():
	for _ in range(t):
		string = list(input())
		dic = {'1': 0, '2': 0, '3': 0}
		(s, e) = (0, 0)
		n = len(string)
		minlen = 0
		while e < n:
			ele = string[e]
			dic[ele] += 1
			if dic['1'] and dic['2'] and dic['3']:
				curmin = e - s + 1
				if minlen:
					minlen = min(minlen, curmin)
				else:
					minlen = curmin
				for i in range(s, e):
					dido = string[i]
					dic[dido] -= 1
					if not (dic['1'] and dic['2'] and dic['3']):
						minlen = min(minlen, e - i + 1)
						s = i + 1
						break
			e += 1
		yield minlen
t = int(input())
ans = gift()
print(*ans, sep='\n')


import sys
input = sys.stdin.readline
flush = sys.stdout.flush
for _ in range(int(input())):
	s = list(input().rstrip())
	n = len(s)
	comp = []
	i = 0
	while i < n:
		j = i
		while j < n and s[j] == s[i]:
			j += 1
		comp.append((s[i], j - i))
		i = j
	cand = []
	m = len(comp)
	for i in range(1, m - 1):
		if comp[i - 1][0] != comp[i][0] and comp[i][0] != comp[i + 1][0] and (comp[i - 1][0] != comp[i + 1][0]):
			cand.append(comp[i][1] + 2)
	if cand == []:
		print(0)
	else:
		print(min(cand))


t = int(input())
for _ in range(t):
	l = list(map(int, list(input())))
	ar = []
	st = 1
	for i in range(1, len(l)):
		if l[i - 1] != l[i]:
			ar.append((i - st, i - 1))
			st = 1
		else:
			st += 1
	mn = float('inf')
	for i in range(1, len(ar)):
		if l[ar[i][0] - 1] != l[ar[i][0]] and l[ar[i][0] - 1] != l[ar[i][1] + 1] and (l[ar[i][1] + 1] != l[ar[i][0]]):
			mn = min(mn, ar[i][1] - ar[i][0] + 3)
	if mn <= len(l):
		print(mn)
	else:
		print(0)


import sys
import math
import operator as op
from collections import defaultdict
from functools import reduce

def read_line():
	return sys.stdin.readline()[:-1]

def read_int():
	return int(sys.stdin.readline())

def read_int_line():
	return [int(v) for v in sys.stdin.readline().split()]

def read_float_line():
	return [float(v) for v in sys.stdin.readline().split()]

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 rad(x):
	return math.pi * x / 180

def findSubString(str):
	n = len(str)
	dist_count = len(set([x for x in str]))
	curr_count = defaultdict(lambda : 0)
	count = 0
	start = 0
	end = 0
	min_len = 100000000.0
	for j in range(n):
		curr_count[str[j]] += 1
		if curr_count[str[j]] == 1:
			count += 1
		if count == dist_count:
			while curr_count[str[start]] > 1:
				if curr_count[str[start]] > 1:
					curr_count[str[start]] -= 1
				start += 1
			len_window = j - start + 1
			if min_len > len_window:
				min_len = len_window
				start_index = start
	return str[start_index:start_index + min_len]
t = read_int()
for i in range(t):
	s = read_line()
	cnt = 0
	st = findSubString(s)
	ans = len(st)
	if ans >= 3:
		print(ans)
	else:
		print(0)


n = 256

def f(string, pat):
	len1 = len(string)
	len2 = len(pat)
	if len1 < len2:
		return ''
	hp = [0] * n
	hs = [0] * n
	for i in range(0, len2):
		hp[ord(pat[i])] += 1
	(s, si, ml) = (0, -1, float('inf'))
	count = 0
	for j in range(0, len1):
		hs[ord(string[j])] += 1
		if hp[ord(string[j])] != 0 and hs[ord(string[j])] <= hp[ord(string[j])]:
			count += 1
		if count == len2:
			while hs[ord(string[s])] > hp[ord(string[s])] or hp[ord(string[s])] == 0:
				if hs[ord(string[s])] > hp[ord(string[s])]:
					hs[ord(string[s])] -= 1
				s += 1
			lw = j - s + 1
			if ml > lw:
				ml = lw
				si = s
	if si == -1:
		return ''
	return string[si:si + ml]
t = int(input())
for _ in range(t):
	s = input()
	print(len(f(s, '123')))


for t in range(int(input())):
	s = input()
	d = [-1, -1, -1]
	cur_len = 200000
	min_len = 200000
	for (i, c) in enumerate(s):
		if min(d) != -1:
			cur_len = max(d) - min(d)
			if cur_len < min_len:
				min_len = cur_len
		if c == '1':
			d[0] = i
		elif c == '2':
			d[1] = i
		elif c == '3':
			d[2] = i
		if min_len == 2:
			break
	if min(d) != -1:
		cur_len = max(d) - min(d)
		if cur_len < min_len:
			min_len = cur_len
	if min_len == 200000:
		print(0)
	else:
		print(min_len + 1)


def solve():
	lst = list(map(int, input()))
	n = len(lst)
	cou = 0
	nl = []
	le = lst[0]
	for i in lst:
		if i == le:
			cou += 1
		else:
			nl.append([le, cou])
			le = i
			cou = 1
	nl.append([le, cou])
	ans = 0
	for i in range(len(nl) - 2):
		setik = set([nl[i][0], nl[i + 1][0], nl[i + 2][0]])
		if len(setik) == 3:
			if ans == 0:
				ans = 1 + nl[i + 1][1] + 1
			ans = min(ans, 1 + nl[i + 1][1] + 1)
	print(ans)
for i in range(int(input())):
	solve()


import sys
pprint = lambda s: print(' '.join(map(str, s)))
input = lambda : sys.stdin.readline().strip()
ipnut = input
for i in range(int(input())):
	s = list(map(int, input()))
	n = len(s)
	o = [-n - 3, -n - 3, -n - 3]
	ans = 10000000000000
	for i in range(n):
		o[s[i] - 1] = i
		ans = min(ans, i - min(o) + 1)
	if -3 - n in o:
		print(0)
	else:
		print(ans)


test = int(input())
for _ in range(test):
	s = input()
	buff = [-1] * 3
	ans = float('inf')
	for i in range(len(s)):
		buff[int(s[i]) - 1] = i
		if buff[0] > -1 and buff[1] > -1 and (buff[2] > -1):
			ans = min(ans, max(buff) - min(buff) + 1)
	if ans != float('inf'):
		print(ans)
	else:
		print(0)


from collections import deque
n = int(input())
for i in range(n):
	s = [int(ch) for ch in input()]
	check = {1: 0, 2: 0, 3: 0}
	left = 0
	right = 0
	que = deque()
	n = len(s)
	minLen = n
	isFind = False
	while True:
		if check[1] != 0 and check[2] != 0 and (check[3] != 0):
			minLen = min(minLen, len(que))
			left += 1
			num = que.popleft()
			check[num] -= 1
			isFind = True
		else:
			if right > len(s) - 1:
				break
			que.append(s[right])
			check[s[right]] += 1
			right += 1
	if isFind == False:
		minLen = 0
	print(minLen)


for _ in range(int(input())):
	s = list(input())
	l1 = l2 = l3 = -1
	mn = len(s) + 1
	for (i, c) in enumerate(s):
		if c == '1':
			l1 = i
		if c == '2':
			l2 = i
		if c == '3':
			l3 = i
		if l1 >= 0 and l2 >= 0 and (l3 >= 0):
			mn = min(mn, max(l1, l2, l3) - min(l1, l2, l3) + 1)
	print(mn if mn <= len(s) else 0)


import math
t = int(input())

def fn():
	s = input()
	n = len(s)
	(last_1, last_2, last_3, ans) = (0, 0, 0, 10 ** 10)
	for i in range(n):
		if s[i] == '1':
			last_1 = i + 1
		elif s[i] == '2':
			last_2 = i + 1
		else:
			last_3 = i + 1
		right = max(last_3, last_1, last_2)
		left = min(last_1, last_2, last_3)
		if left:
			ans = min(right - left + 1, ans)
	if ans == 10 ** 10:
		print(0)
	else:
		print(ans)
while t:
	t -= 1
	fn()


t = int(input())
while t:
	val_1 = -1
	val_2 = -1
	val_3 = -1
	s = input()
	result = []
	for i in range(0, len(s)):
		if s[i] == '1':
			val_1 = i
		elif s[i] == '2':
			val_2 = i
		elif s[i] == '3':
			val_3 = i
		if val_1 != -1 and val_2 != -1 and (val_3 != -1):
			max_val = max(val_1, val_2, val_3)
			min_val = min(val_1, val_2, val_3)
			result.append(max_val - min_val + 1)
	if val_1 == -1 or val_2 == -1 or val_3 == -1:
		print(0)
	else:
		print(min(result))
	t = t - 1


t = int(input())
while t > 0:
	s = input().strip()
	d = {'1': -1, '2': -1, '3': -1}
	diff = 0
	mindiff = 2000001
	for (index, elem) in enumerate(s):
		d[elem] = index
		diff = max(d.values()) - min(d.values()) + 1
		if diff < mindiff and -1 not in d.values():
			mindiff = diff
	if -1 in d.values():
		print(0)
	else:
		print(mindiff)
	t -= 1


import sys

def solve(S):
	A = [int(c) for c in S]
	n = len(A)
	MIN = 200001
	last = [-1] * 4
	for i in range(n):
		v = A[i]
		prev = last[v]
		last[v] = i
		have_all = len([x for x in last[1:] if x >= 0]) == 3
		if have_all:
			MIN = min(MIN, i - min(last[1:]) + 1)
	return MIN if MIN < 200001 else 0
IN = [x.strip() for x in sys.stdin.readlines()]
T = int(IN[0])
cur = 1
for ti in range(T):
	S = IN[cur]
	result = solve(S)
	print(result)
	cur += 1


def check(arr):
	if len(set(arr)) < 3:
		return 0
	prev = arr[0]
	count = 1
	i = 1
	blocks = []
	ans = len(arr)
	while i < len(arr):
		if arr[i] == prev:
			count += 1
		else:
			blocks.append([arr[i - 1], i - count - 1, i, count])
			count = 1
			prev = arr[i]
		i += 1
	blocks.append([arr[i - 1], i - count - 1, i, count])
	for i in range(1, len(blocks) - 1):
		if arr[blocks[i][1]] != arr[blocks[i][2]]:
			if blocks[i][3] + 2 < ans:
				ans = blocks[i][3] + 2
	return ans
t = int(input())
while t:
	s = list(input())
	arr = list(map(int, s))
	result = check(arr)
	print(result)
	t -= 1


import os
import sys
if os.path.exists('/mnt/c/Users/Square/square/codeforces'):
	f = iter(open('B.txt').readlines())

	def input():
		return next(f).strip()
else:
	input = lambda : sys.stdin.readline().strip()
fprint = lambda *args: print(*args, flush=True)
INF = 10 ** 6
t = int(input())
for _ in range(t):
	s = input()
	(p1, p2, p3) = ([INF] * len(s), [INF] * len(s), [INF] * len(s))
	(pos1, pos2, pos3) = (INF, INF, INF)
	r = INF
	for (n, i) in enumerate(s):
		pos1 += 1
		pos2 += 1
		pos3 += 1
		if i == '1':
			pos1 = 0
		if i == '2':
			pos2 = 0
		if i == '3':
			pos3 = 0
		p1[n] = pos1
		p2[n] = pos2
		p3[n] = pos3
		r = min(r, max(pos1, pos2, pos3))
	if r > len(s):
		print(0)
	else:
		print(r + 1)


from collections import Counter
import os
import sys
from io import BytesIO, IOBase
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))
input = lambda : sys.stdin.readline().rstrip('\r\n')
import math
for i in range(int(input())):
	s = input()
	l = [-1] * 3
	m = 0
	for i in range(len(s)):
		l[int(s[i]) - 1] = i
		if l[0] > -1 and l[1] > -1 and (l[2] > -1):
			if m == 0:
				m = max(l) - min(l) + 1
			else:
				m = min(m, max(l) - min(l) + 1)
	print(m)


import sys
for _ in range(int(input())):
	s = list(input())
	(one, two, three) = (-1, -1, -1)
	ans = sys.maxsize
	for i in range(len(s)):
		if s[i] == '1' and i > one:
			one = i
		elif s[i] == '2' and i > two:
			two = i
		elif s[i] == '3' and i > three:
			three = i
		if one >= 0 and two >= 0 and (three >= 0):
			ans = min(ans, max(abs(one - two) + 1, abs(two - three) + 1, abs(three - one) + 1))
	if ans == sys.maxsize:
		print(0)
	else:
		print(ans)


import math

def main():
	for q in range(int(input())):
		S = input()
		l = [0] * 4
		i = -1
		j = 0
		ans = 10 ** 9
		while i < len(S):
			if i < len(S) - 1 and l[1] * l[2] * l[3] == 0:
				i += 1
				c = ord(S[i]) - ord('0')
				l[c] += 1
			if l[1] * l[2] * l[3] != 0:
				ans = min(ans, i - j + 1)
			if l[1] * l[2] * l[3] != 0:
				while l[1] * l[2] * l[3] != 0:
					c = ord(S[j]) - ord('0')
					l[c] -= 1
					j += 1
					if l[1] * l[2] * l[3] != 0:
						ans = min(ans, i - j + 1)
			if l[1] * l[2] * l[3] != 0:
				ans = min(ans, i - j + 1)
			if i == len(S) - 1:
				break
		print(ans if ans != 10 ** 9 else '0')
main()


z = int(input())
for h in range(z):
	a = list(map(int, input()))
	m = [0, 0, 0]
	m[a[0] - 1] += 1
	ans = []
	flag = 0
	for i in range(1, len(a)):
		if flag == 0 and a[i] == a[i - 1]:
			m[a[i] - 1] = 1
		if flag == 0 and a[i] != a[i - 1]:
			flag = 1
		if flag == 1:
			if a[i] != a[i - 1] and m[a[i] - 1] > 0:
				m[a[i] - 1] = 1
				m[a[i - 1] - 1] = 1
			else:
				m[a[i] - 1] += 1
				if m[0] > 0 and m[1] > 0 and (m[2] > 0):
					ans.append(sum(m))
					m[0] = 0
					m[1] = 0
					m[2] = 0
					m[a[i] - 1] = 1
					m[a[i - 1] - 1] = 1
	if len(ans) == 0:
		print(0)
	else:
		print(min(ans))


T = int(input())
for i in range(T):
	S = input()
	try:
		p1 = S.index('1')
		p2 = S.index('2')
		p3 = S.index('3')
	except:
		print(0)
		continue
	ans = 1 << 30
	for j in range(len(S)):
		if p1 < j:
			p1 += 1
			while p1 < len(S):
				if S[p1] != '1':
					p1 += 1
				else:
					break
		if p2 < j:
			p2 += 1
			while p2 < len(S):
				if S[p2] != '2':
					p2 += 1
				else:
					break
		if p3 < j:
			p3 += 1
			while p3 < len(S):
				if S[p3] != '3':
					p3 += 1
				else:
					break
		if max(p1, p2, p3) == len(S):
			break
		else:
			ans = min(ans, max(p1, p2, p3) - j + 1)
	print(ans)


t = int(input())
for i in range(t):
	s = input()
	l = list(s)
	if l.count('1') == 0 or l.count('2') == 0 or l.count('3') == 0:
		print(0)
	else:
		l2 = []
		for j in range(len(l) - 1):
			if l[j] != l[j + 1]:
				x = l[j]
				y = l[j + 1]
				for k in range(j + 1, len(l) - 1):
					if l[k + 1] == l[j]:
						break
					if l[k] != l[k + 1] and l[k + 1] != l[j]:
						z = l[k + 1]
						p = k + 2 - j
						l2.append(p)
		print(min(l2))


q = int(input())
for k in range(q):
	a = str(input())
	n = len(a)
	t = [0] * 3
	ans = [0, 0]
	c = 0
	for i in range(n):
		if t[int(a[i]) - 1] == 0:
			c += 1
		t[int(a[i]) - 1] += 1
		if c == 3:
			break
	if c != 3:
		print(0)
		continue
	l = 0
	r = i
	min = r - l
	ans = [l, r]
	while True:
		if t[int(a[l]) - 1] > 1:
			t[int(a[l]) - 1] -= 1
			l += 1
		elif r != n - 1:
			t[int(a[r + 1]) - 1] += 1
			r += 1
		else:
			break
		if r - l < min:
			min = r - l
			ans = [l, r]
	print(min + 1)


z = int(input())
while z:
	z -= 1
	s = input()
	n = len(s)
	a = []
	last = s[0]
	a.append([last, 1])
	for i in range(1, n):
		if s[i] == last:
			a[-1][1] += 1
		else:
			last = s[i]
			a.append([s[i], 1])
	d = ['123', '132', '213', '231', '312', '321']
	x = n + 1
	for i in range(1, len(a) - 1):
		t = a[i - 1][0] + a[i][0] + a[i + 1][0]
		v = a[i][1] + 2
		if t in d:
			x = min(x, v)
		if x == 3:
			break
	if x <= n:
		print(x)
	else:
		print(0)


def printv(a, sep=' '):
	print(sep.join(map(str, a)))

def check(s, n, x):
	st = {'1': 0, '2': 0, '3': 0}
	for i in range(x):
		st[s[i]] += 1
	for i in range(n - x):
		if st['1'] > 0 and st['2'] > 0 and (st['3'] > 0):
			return 1
		st[s[i]] -= 1
		st[s[i + x]] += 1
	if st['1'] > 0 and st['2'] > 0 and (st['3'] > 0):
		return 1
	return 0

def solve(s):
	n = len(s)
	(l, r) = (2, n + 1)
	f = False
	while l + 1 < r:
		res = (l + r) // 2
		if check(s, n, res):
			f = True
			r = res
		else:
			l = res
	if f:
		return r
	return 0

def main():
	t = int(input())
	ans = [0] * t
	for i in range(t):
		st = input()
		ans[i] = solve(st)
	printv(ans, '\n')
main()


from collections import Counter as C, defaultdict as D, deque as Q
from operator import itemgetter as I
from itertools import product as P
from bisect import bisect_left as BL, bisect_right as BR
from heapq import heappush as HPUSH, heappop as HPOP
from math import floor as MF, ceil as MC, gcd as MG, factorial as F, sqrt as SQRT, inf as INFINITY, log as LOG
from sys import stdin, stdout
INPUT = stdin.readline
PRINT = stdout.write

def player1():
	print('')

def player2():
	print('')

def isPrime(n):
	for i in range(2, MC(SQRT(n)) + 1):
		if n % i == 0:
			return False
	return True

def factors(x):
	ans = []
	for i in range(1, MC(SQRT(x)) + 1):
		if x % i == 0:
			ans.append(i)
			if x % (x // i) == 0:
				ans.append(x // i)
	return ans

def main():
	for _ in range(int(INPUT())):
		s = INPUT()[:-1]
		n = len(s)
		i = 0
		j = -1
		check = D(int)
		ans = INFINITY
		while j < n and i < n:
			if not check['1'] or not check['2'] or (not check['3']):
				j += 1
				if j < n:
					check[s[j]] += 1
			else:
				ans = min(ans, j - i + 1)
				check[s[i]] -= 1
				i += 1
		if check['1'] and check['2'] and check['3']:
			ans = min(ans, j - i)
		if ans == INFINITY:
			ans = 0
		PRINT(str(ans) + '\n')
main()


for t in range(int(input())):
	s = input()
	l = len(s)
	w = [-l] * 3
	ans = l
	for i in range(l):
		w[int(s[i]) - 1] = i
		ans = min(ans, max(w) - min(w))
	print(0) if -l in w else print(ans + 1)


import math

def solve(s):
	i1 = -1
	i2 = -1
	i3 = -1
	m = 999999
	for (i, j) in enumerate(s):
		if j == 1:
			i1 = i
		elif j == 2:
			i2 = i
		elif j == 3:
			i3 = i
		if i1 != -1 and i2 != -1 and (i3 != -1):
			res = max(i1, i2, i3) - min(i1, i2, i3)
			if res < m:
				m = res
	return m + 1 if m != 999999 else 0
t = int(input())
for _ in range(t):
	s = list(map(int, list(input())))
	res = solve(s)
	print(res)


a = int(input())
for i in range(a):
	s = str(input())
	rrr = [0, 0, 0]
	ch1 = 0
	ch2 = -1
	min = 9999999999
	kek = len(s)
	if s.count('1') and s.count('2') and s.count('3'):
		while ch2 < kek and ch1 < kek:
			if rrr.count(0):
				if ch2 == kek - 1:
					break
				ch2 += 1
				rrr[int(s[ch2]) - 1] += 1
			else:
				if ch2 - ch1 + 1 < min:
					min = ch2 - ch1 + 1
				rrr[int(s[ch1]) - 1] -= 1
				ch1 += 1
		print(min)
	else:
		print(0)


from sys import setrecursionlimit
from collections import deque
import math
import heapq
import functools
for _ in range(int(input())):
	s = input()
	left = [s[0], 0]
	center = [s[0], 0]
	right = [s[0], 0]
	prev = s[0]
	ans = 10 ** 6
	for i in s:
		if i == right[0]:
			right[1] += 1
		else:
			t = sorted([left[0], center[0], right[0]])
			if t == ['1', '2', '3']:
				t = 1 + center[1] + 1
				if t < ans:
					ans = t
			left = center
			center = right
			right = [i, 1]
	t = sorted([left[0], center[0], right[0]])
	if t == ['1', '2', '3']:
		t = 1 + center[1] + 1
		if t < ans:
			ans = t
	if ans == 10 ** 6:
		ans = 0
	print(ans)


from sys import stdin
input = stdin.readline
for _ in range(int(input())):
	s = input()
	x = y = z = -10000000000
	ans = 10000000000
	for i in range(len(s)):
		if s[i] == '1':
			x = i
		elif s[i] == '2':
			y = i
		elif s[i] == '3':
			z = i
		ans = min(ans, i - min(x, y, z) + 1)
	if ans == 10000000000:
		print(0)
	else:
		print(ans)


def read_ints():
	return [int(i) for i in input().strip().split()]

def solve():
	pass

def main():
	t = int(input())
	for i in range(t):
		seen = [-1, -1, -1]
		best = 200001
		s = input()
		for (idx, i) in enumerate(s):
			num = int(i)
			seen[num - 1] = idx
			if min(seen) > -1:
				best = min(best, max(seen) - min(seen) + 1)
		if best == 200001:
			print(0)
		else:
			print(best)
main()


def ternary(s):
	l = len(s)
	answer = 0
	lone = None
	ltwo = None
	lthree = None
	for i in range(l):
		if s[i] == '1':
			lone = i
		elif s[i] == '2':
			ltwo = i
		else:
			lthree = i
		if lone != None and ltwo != None and (lthree != None):
			a = int(max(lone, ltwo, lthree)) - int(min(lone, ltwo, lthree)) + 1
			if a < answer or answer == 0:
				answer = a
	return answer
t = int(input())
array = []
for i in range(t):
	array.append(input())
for x in array:
	print(ternary(x))


for _ in range(int(input())):
	s = [int(i) for i in list(input())]
	n = len(s)
	(dist_count, curr_count) = (3, {})
	for i in range(1, 4):
		curr_count[i] = 0
	(start, start_index, count) = (0, -1, 0)
	ans = 200001
	for i in range(n):
		curr_count[s[i]] += 1
		if curr_count[s[i]] == 1:
			count += 1
		if count == 3:
			while curr_count[s[start]] > 1:
				if curr_count[s[start]] > 1:
					curr_count[s[start]] -= 1
				start += 1
			len_window = i - start + 1
			if ans > len_window:
				ans = len_window
				start_index = start
	if ans == 200001:
		print(0)
	else:
		print(ans)


import math
for _ in range(int(input())):
	s = input()
	s += '0'
	l = []
	count = 1
	for i in range(len(s) - 1):
		if s[i] == s[i + 1]:
			count += 1
		else:
			l.append([int(s[i]), count])
			count = 1
	ans = math.inf
	for i in range(1, len(l) - 1):
		x = [l[i - 1][0], l[i][0], l[i + 1][0]]
		if set(x) == {1, 2, 3}:
			ans = min(ans, l[i][1] + 2)
	if ans == math.inf:
		ans = 0
	print(ans)


for lo in range(int(input())):
	st = input()
	a = -1
	b = -1
	c = -1
	n = len(st)
	ans = n + 1
	for i in range(n):
		if st[i] == '1':
			a = max(i, a)
		if st[i] == '2':
			b = max(i, b)
		if st[i] == '3':
			c = max(i, c)
		if a != -1 and b != -1 and (c != -1):
			x = min(a, min(b, c))
			y = max(a, max(b, c))
			ans = min(ans, y - x + 1)
	if ans == n + 1:
		print(0)
	else:
		print(ans)


import random
import math
LI = lambda : list(map(int, input().split()))
MI = lambda : map(int, input().split())
yes = lambda : print('Yes')
no = lambda : print('No')
I = lambda : list(input())
J = lambda x: ''.join(x)
II = lambda : int(input())
SI = lambda : input()
t = II()
for q in range(t):
	s = list(SI())
	if len(set(s)) != 3:
		print(0)
	else:
		l1 = -1
		l2 = -1
		l3 = -1
		mi = len(s)
		for i in range(mi):
			if s[i] == '1':
				l1 = i
			elif s[i] == '2':
				l2 = i
			else:
				l3 = i
			if l1 != -1 and l2 != -1 and (l3 != -1):
				mi = min(mi, max(l1, l2, l3) + 1 - min(l1, l2, l3))
		print(mi)


import collections
for _ in range(int(input())):
	s = str(input())
	left = 0
	n = len(s)
	m = 1000000.0
	d = {}
	for i in range(n):
		if s[i] not in d:
			d[s[i]] = 1
		else:
			d[s[i]] += 1
		if '1' in d and '2' in d and ('3' in d):
			m = min(i - left + 1, m)
			while '1' in d and '2' in d and ('3' in d):
				d[s[left]] -= 1
				if d[s[left]] == 0:
					del d[s[left]]
				left += 1
			m = min(i - left + 2, m)
	if m == 1000000.0:
		print(0)
	else:
		print(m)


import os
import sys
from io import BytesIO, IOBase

def readvars():
	k = map(int, input().split())
	return k

def readlist():
	li = list(map(int, input().split()))
	return li

def anslist(li):
	ans = ' '.join([str(v) for v in li])
	return ans

def main():
	t = 1
	t = int(input())
	for xx in range(t):
		s = input()
		le = 1
		li = []
		num = 0
		for i in range(1, len(s)):
			if s[i] == s[i - 1]:
				le += 1
			if s[i] != s[i - 1]:
				li.append([s[i - 1], le])
				le = 1
		li.append([s[-1], le])
		flg = 0
		smlen = len(s)
		for i in range(1, len(li) - 1):
			if li[i - 1][0] != li[i + 1][0]:
				smlen = min(smlen, li[i][1])
				flg = 1
		if flg == 0:
			print(0)
		else:
			print(smlen + 2)
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))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


n = int(input())
MOD = 10 ** 9 + 7
s = [0] * n
for i in range(n):
	s[i] = input()
for i in range(n):
	l = [0] * 3
	l[int(s[i][0]) - 1] = 1
	ans = MOD
	for j in range(len(s[i]) - 1):
		if s[i][j] == s[i][j + 1]:
			continue
		else:
			l[int(s[i][j + 1]) - 1] = j + 2
			l[int(s[i][j]) - 1] = j + 1
		if 0 not in l:
			ans = min(max(l) - min(l), ans)
	if ans == 10 ** 9 + 7:
		print(0)
	else:
		print(ans + 1)


import os
import sys
from math import *
from collections import *
from bisect import *
from io import BytesIO, IOBase
from fractions import *

def vsInput():
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
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))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def value():
	return tuple(map(int, input().split()))

def array():
	return [int(i) for i in input().split()]

def Int():
	return int(input())

def Str():
	return input()

def arrayS():
	return [i for i in input().split()]
for _ in range(Int()):
	s = input()
	count = set()
	qu = []
	count = set()
	st = 0
	mid = 0
	en = 0
	c1 = 0
	c2 = 0
	ans = inf
	for i in range(len(s)):
		if s[i] not in count:
			count.add(s[i])
		if len(count) == 1 or ele1 == s[i]:
			st = i
			ele1 = s[i]
		elif len(count) == 2:
			mid = i
			ele2 = s[i]
		elif len(count) == 3:
			ans = min(ans, i - min(st, mid) + 1)
			count.remove(s[min(st, mid)])
			if mid > st:
				st = mid
				ele1 = ele2
			mid = i
			ele2 = s[i]
	if ans == inf:
		print(0)
	else:
		print(ans)


T = int(input())
for i in range(T):
	s = input()
	n = len(s)
	l1 = [-1] * n
	l2 = [-1] * n
	l3 = [-1] * n
	a = s[0]
	if a == '1':
		l1[0] = 0
	elif a == '2':
		l2[0] = 0
	else:
		l3[0] = 0
	for i in range(n):
		a = s[i]
		if a == '1':
			l1[i] = i
			l2[i] = l2[i - 1]
			l3[i] = l3[i - 1]
		elif a == '2':
			l2[i] = i
			l1[i] = l1[i - 1]
			l3[i] = l3[i - 1]
		else:
			l3[i] = i
			l1[i] = l1[i - 1]
			l2[i] = l2[i - 1]
	ans = 999999999999
	for j in range(n):
		a = l1[j]
		b = l2[j]
		c = l3[j]
		if l1[-1] == -1 or l2[-1] == -1 or l3[-1] == -1:
			ans = 0
			break
		elif a != -1 and b != -1 and (c != -1):
			mi = min(a, b, c)
			ma = max(a, b, c)
			an = ma - mi + 1
			if an < ans:
				ans = an
		else:
			pass
	print(ans)


import sys

def gt():
	return sys.stdin.readline()
sum1 = [0] * 200005
sum2 = [0] * 200005
sum3 = [0] * 200005
t = int(gt())
while t:
	t -= 1
	length = int(10000000000.0)
	s = gt()
	n = len(s)
	s = ' ' + s
	for i in range(1, n + 1):
		sum1[i] = sum1[i - 1] + (s[i] == '1')
		sum2[i] = sum2[i - 1] + (s[i] == '2')
		sum3[i] = sum3[i - 1] + (s[i] == '3')
		(l, r, ans) = (0, i - 1, -1)
		while l <= r:
			mid = l + r >> 1
			if sum1[i] - sum1[mid] > 0 and sum2[i] - sum2[mid] > 0 and (sum3[i] - sum3[mid] > 0):
				(ans, l) = (mid, mid + 1)
			else:
				r = mid - 1
		if ans != -1:
			length = min(length, i - ans)
	if length == int(10000000000.0):
		print(0)
	else:
		print(length)


from sys import stdin, stdout
import collections
import heapq
import itertools
import functools

def read_line():
	return stdin.readline().strip()

def read_int():
	return int(read_line())

def read_arr():
	return read_line().split(' ')

def read_int_arr():
	return [int(x) for x in read_arr()]

def query_interactive(s):
	print(s)
	stdout.flush()

def minWindow(s, t):
	freq = dict(collections.Counter(t))
	sc = dict(collections.Counter(s))
	if any((s not in sc or freq[s] > sc[s] for s in freq)):
		return 0
	if len(t) > len(s):
		return 0
	N = functools.reduce(lambda x, y: x + freq[y], freq, 0)
	l = 0
	min_s = len(s)
	for (r, v) in enumerate(s):
		if v in freq:
			if freq[v] > 0:
				N -= 1
			freq[v] -= 1
		while N == 0:
			lc = s[l]
			if lc in freq:
				freq[lc] += 1
				if freq[lc] > 0:
					N += 1
			if r - l + 1 < min_s:
				min_s = r - l + 1
			l += 1
	return min_s

def main():
	T = read_int()
	for _ in range(T):
		s = read_line()
		print(minWindow(s, '123'))
main()


import os
import sys
from io import BytesIO, IOBase
import heapq as h
from bisect import bisect_left, bisect_right
from types import GeneratorType
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		import os
		self.os = os
		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 = self.os.read(self._fd, max(self.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 = self.os.read(self._fd, max(self.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:
			self.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))
input = lambda : sys.stdin.readline().rstrip('\r\n')
from collections import defaultdict as dd, deque as dq
import math, string

def getInts():
	return [int(s) for s in input().split()]

def getInt():
	return int(input())

def getStrs():
	return [s for s in input().split()]

def getStr():
	return input()

def listStr():
	return list(input())
MOD = 10 ** 9 + 7
from bisect import bisect_left

def solve():
	S = [int(s) - 1 for s in input()]
	prev = [-10 ** 9] * 3
	tmp = []
	count = 0
	for s in S:
		prev[s] = count
		tmp.append(prev[:])
		count += 1
	ans = 10 ** 9
	for j in range(len(tmp)):
		tmp[j].sort()
		ans = min(ans, tmp[j][2] - tmp[j][0] + 1)
	return ans if ans < 10 ** 9 else 0
for _ in range(getInt()):
	print(solve())


t = int(input())
while t > 0:
	t -= 1
	s = input()
	if '1' not in s or '2' not in s or '3' not in s:
		print(0)
	else:
		lis = []
		cur = s[0]
		count = 1
		for i in range(1, len(s)):
			if cur == s[i]:
				count += 1
			else:
				lis.append([cur, count])
				cur = s[i]
				count = 1
		if cur == i:
			count += 1
		else:
			lis.append([cur, count])
			cur = s[i]
			count = 1
		minn = len(s)
		for i in range(1, len(lis) - 1):
			if lis[i - 1][0] != lis[i][0] and lis[i][0] != lis[i + 1][0] and (lis[i - 1][0] != lis[i + 1][0]):
				val = int(lis[i][1]) + 2
				if val < minn:
					minn = val
		print(minn)


no_of_chars = 256

def findSubString(string, pat):
	len1 = len(string)
	len2 = len(pat)
	if len1 < len2:
		return 0
	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 0
	return string[start_index:start_index + min_len]
pat = ['1', '2', '3']
t = int(input())
for i in range(t):
	n = list(input())
	if findSubString(n, pat) == 0:
		print(0)
	else:
		print(len(findSubString(n, pat)))


t = int(input())
while t:
	t -= 1
	s = input()
	n = len(s)
	d = {}
	cnt = 10 ** 9
	d = {i: -1 for i in '123'}
	for i in range(n):
		d[s[i]] = i
		if d['1'] != -1 and d['2'] != -1 and (d['3'] != -1):
			a = min(d.values())
			b = max(d.values())
			cnt = min(cnt, b - a + 1)
	if cnt == 10 ** 9:
		print(0)
	else:
		print(cnt)


t = int(input())
for _ in range(t):
	s = input()
	s = list(s)
	k = set(s)
	n = len(s)
	if len(k) < 3:
		print('0')
		continue
	else:
		l = n + 1
		(a, b, c) = (n + 1, n + 1, n + 1)
		for i in range(n):
			if s[i] == '1':
				a = i
			if s[i] == '2':
				b = i
			if s[i] == '3':
				c = i
			if a != n + 1 and b != n + 1 and (c != n + 1):
				d = max(a, b, c)
				x = min(a, b, c)
				y = d - x + 1
				l = min(l, y)
		if l == n + 1:
			print('0')
		else:
			print(l)


for _ in range(int(input())):
	s = input()
	li = []
	x = float('inf')
	(a, b, c) = (None, None, None)
	for i in range(len(s)):
		if s[i] == '1':
			a = i
		elif s[i] == '2':
			b = i
		elif s[i] == '3':
			c = i
		if a != None and b != None and (c != None):
			li = [a, b, c]
			li.sort()
			x = min(x, max(li) - min(li) + 1)
	if x == float('inf'):
		print(0)
	else:
		print(x)


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)


from collections import defaultdict
for _ in range(int(input())):
	L = list(input())
	Hash = defaultdict(lambda : 0)
	count = 0
	ans = float('inf')
	for i in range(len(L)):
		Hash[L[i]] = i + 1
		x = Hash['1']
		y = Hash['2']
		z = Hash['3']
		if x > 0 and y > 0 and (z > 0):
			ans = min(ans, max(x, y, z) - min(x, y, z) + 1)
	if ans == float('inf'):
		print(0)
	else:
		print(ans)


t = int(input())
ans = []
for _ in range(t):
	s = input().strip()
	n = len(s)
	lo = 0
	hi = 0
	freq = {s[0]: 1}
	count = float('inf')
	for hi in range(1, n):
		x = s[hi]
		freq[x] = (freq.get(x) or 0) + 1
		while lo < hi:
			x = s[lo]
			if freq[x] > 1:
				freq[x] -= 1
				if freq[x] == 0:
					freq.pop(x)
			else:
				break
			lo += 1
		if '1' in freq and '2' in freq and ('3' in freq):
			count = min(count, hi - lo + 1)
	if count == float('inf'):
		count = 0
	ans.append(count)
ans = '\n'.join([str(i) for i in ans])
print(ans)


from collections import defaultdict

def solve():
	s = input()
	(start, index) = (0, -1)
	curr_count = defaultdict(lambda : 0)
	count = 0
	dist_count = 3
	min_l = 999999999999999
	flag = 0
	for i in range(len(s)):
		curr_count[s[i]] += 1
		if curr_count[s[i]] == 1:
			count += 1
		if count == dist_count:
			flag = 1
			while curr_count[s[start]] > 1:
				if curr_count[s[start]] > 1:
					curr_count[s[start]] -= 1
				start += 1
			w = i - start + 1
			if min_l > w:
				min_l = w
				index = start
	if flag == 0:
		return 0
	else:
		return len(s[index:index + min_l])
for _ in range(int(input())):
	print(solve())


def main():
	t = int(input())
	for _ in range(t):
		s = input()
		d = {'1': -1, '2': -1, '3': -1}
		m = len(s) + 1
		for (c, el) in enumerate(s):
			d[el] = c
			st = min(d.values())
			if st == -1:
				continue
			m = min(m, c - st + 1)
		if m == len(s) + 1:
			print(0)
		else:
			print(m)
main()


test = int(input())
for i in range(test):
	string = input()
	s = [int(a) for a in string]
	l = []
	ans = float('inf')
	length = 0
	d = {1: 0, 2: 0, 3: 0}
	prev = None
	for i in range(len(s)):
		if l == []:
			l.append(s[i])
			length = 1
			d[s[i]] = 1
			prev = s[i]
		elif s[i] != prev:
			d[s[i]] = 1
			if d[1] == d[2] and d[2] == d[3]:
				ans = min(length + 1, ans)
			l.clear()
			l.append(s[i - 1])
			l.append(s[i])
			d.clear()
			d = {1: 0, 2: 0, 3: 0}
			d[s[i - 1]] = 1
			d[s[i]] = 1
			prev = s[i]
			length = 2
		else:
			length += 1
	if ans != float('inf'):
		print(ans)
	else:
		print('0')


t = int(input())
for i in range(t):
	s = list(input())
	h = [-1] * 4
	r = []
	s = [int(i) for i in s]
	for i in range(len(s)):
		h[s[i]] = i
		if h[1] >= 0 and h[2] >= 0 and (h[3] >= 0):
			r.append(max(h[1], h[2], h[3]) - min(h[1], h[2], h[3]) + 1)
	if r == []:
		print(0)
	else:
		print(min(r))


import math
import functools

def s():
	s = input()
	nearest_1 = 0
	nearest_2 = 0
	nearest_3 = 0
	counter = 0
	pres_1 = False
	pres_2 = False
	pres_3 = False
	n = len(s)
	ans = 2000000.0
	for i in range(n):
		if s[i] == '1':
			nearest_1 = counter
			pres_1 = True
		elif s[i] == '2':
			nearest_2 = counter
			pres_2 = True
		else:
			nearest_3 = counter
			pres_3 = True
		counter += 1
		if pres_1 and pres_2 and pres_3:
			ans = min(ans, 1 + max(nearest_1, nearest_2, nearest_3) - min(nearest_1, nearest_2, nearest_3))
	if not (pres_1 and pres_2 and pres_3):
		print(0)
	else:
		print(ans)
t = int(input())
for i in range(t):
	s()


n = int(input())
result = []
for i in range(n):
	s = input()
	check = 1
	count = 0
	minCount = 200000
	check = True
	ktra = []
	for ch in s:
		count += 1
		if ch in ktra and len(ktra) == 1:
			count -= 1
		elif len(ktra) == 2 and ktra[0] == ch:
			tmp = ktra[0]
			ktra[0] = ktra[1]
			ktra[1] = tmp
			count = 2
		elif not ch in ktra:
			ktra.append(ch)
		if len(ktra) == 3:
			check = False
			minCount = min(minCount, count)
			count = 2
			ktra.pop(0)
	if len(ktra) < 3 and check == True:
		result.append(0)
	else:
		result.append(minCount)
for i in result:
	print(i)


import sys, random, bisect
from collections import deque, defaultdict
from heapq import heapify, heappop, heappush
mod = int(1000000000.0 + 7)
inf = int(1e+20)
input = lambda : sys.stdin.readline().rstrip()
mi = lambda : map(int, input().split())
li = lambda : list(mi())
ii = lambda : int(input())
py = lambda : print('YES')
pn = lambda : print('NO')
t = ii()
for _ in range(t):
	s = input()
	res = inf
	l = r = 0
	cnt = defaultdict(int)
	while r < len(s):
		cnt[s[r]] += 1
		while cnt['1'] > 0 and cnt['2'] > 0 and (cnt['3'] > 0):
			res = min(res, r - l + 1)
			cnt[s[l]] -= 1
			l += 1
		r += 1
	print(res if res <= len(s) else 0)


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)


t = int(input())
for _ in range(t):
	st = input()
	ans = []
	co = 0
	t = 0
	n = len(st)
	while t < n:
		if t == 0:
			prev = st[0]
			ans.append([st[0], 1])
			t = t + 1
		elif st[t] == prev:
			ans[co][1] = ans[co][1] + 1
			t = t + 1
		else:
			prev = st[t]
			co = co + 1
			ans.append([st[t], 1])
			t = t + 1
	la = len(ans)
	anso = []
	for x in range(0, la - 2):
		s = set()
		for y in ans[x:x + 3]:
			s.add(y[0])
			ppl = ans[x + 1][1] + 2
		if len(s) == 3:
			anso.append(ppl)
	if len(anso) == 0:
		print(0)
	else:
		print(min(anso))


def f(n):
	if n == 1:
		return (2, 3)
	elif n == 2:
		return (1, 3)
	else:
		return (1, 2)

def chk(x, y):
	if l[x] != 10 ** 9 and l[y] != 10 ** 9:
		return True
	else:
		return False
import sys
input = sys.stdin.readline
for _ in range(int(input())):
	s = input().strip()
	n = len(s)
	l = [10 ** 9] * 4
	m = 10 ** 9
	for i in range(n):
		c = int(s[i])
		l[c] = i
		(x, y) = f(c)
		if chk(x, y):
			a = max(i - l[x], i - l[y])
			if a + 1 < m:
				m = a + 1
	if m == 10 ** 9:
		print(0)
	else:
		print(m)


t = int(input())
for j in range(t):
	s = list(map(int, list(input())))
	l = 0
	r = 0
	c = [0, 0, 0]
	cmin = 10 ** 9
	c[s[0] - 1] += 1
	if 1 not in s or 2 not in s or 3 not in s:
		print(0)
		continue
	while r != len(s) - 1:
		if 0 not in c:
			if r - l + 1 < cmin:
				cmin = r - l + 1
			c[s[l] - 1] -= 1
			l += 1
		else:
			r += 1
			c[s[r] - 1] += 1
		if cmin == 3:
			break
	while 0 not in c:
		if r - l + 1 < cmin:
			cmin = r - l + 1
		c[s[l] - 1] -= 1
		l += 1
	print(cmin)


from sys import stdin, stdout
inp = stdin.readline
out = stdout.write
for _ in range(int(inp())):
	l = []
	ans = 1000000000.0
	st = inp()
	n = len(st) - 1
	for c in st:
		sz = len(l)
		if len(l) == 0 or l[sz - 1][0] != c:
			l.append([c, 1])
		else:
			l[sz - 1][1] += 1
	m = len(l) - 1
	for i in range(1, m - 1):
		if l[i - 1][0] != l[i + 1][0]:
			ans = min(ans, l[i][1] + 2)
	if ans > n:
		ans = 0
	out(str(ans) + '\n')


t = int(input())
result = []
n_o_c = 256

def f_s(string):
	len_rs = len(string)
	pattern = '123'
	len_pt = len(pattern)
	if len_rs < len_pt:
		return 0
	h_pt = [0] * n_o_c
	h_rs = [0] * n_o_c
	for i in range(0, len_pt):
		h_pt[ord(pattern[i])] += 1
	(st, st_i, min_l) = (0, -1, float('inf'))
	count = 0
	for j in range(0, len_rs):
		h_rs[ord(string[j])] += 1
		if h_pt[ord(string[j])] != 0 and h_rs[ord(string[j])] <= h_pt[ord(string[j])]:
			count += 1
		if count == len_pt:
			while h_rs[ord(string[st])] > h_pt[ord(string[st])] or h_pt[ord(string[st])] == 0:
				if h_rs[ord(string[st])] > h_pt[ord(string[st])]:
					h_rs[ord(string[st])] -= 1
				st += 1
			l_w = j - st + 1
			if min_l > l_w:
				min_l = l_w
				st_i = st
	if st_i == -1:
		return 0
	return len(string[st_i:st_i + min_l])
for i in range(t):
	result.append(f_s(input()))
for i in range(t):
	print(result[i])


for _ in range(int(input())):
	s = input()
	ar = [-1, -1, -1]
	ans = 2000000.0
	z = 1
	for i in range(len(s)):
		ar[int(s[i]) - 1] = i
		if ar.count(-1) == 0:
			z = 0
			ans = min(ans, max(ar) - min(ar) + 1)
	if z:
		print(0)
	else:
		print(ans)


import itertools as it
t = int(input())
for i in range(t):
	s = list(input())
	s = [(int(i[0]), len(list(i[1]))) for i in it.groupby(s)]
	if len(s) < 3:
		print(0)
	else:
		n = len(s)
		v = [0] * n
		f = [0] * n
		for i in range(n):
			v[i] = s[i][0]
			f[i] = s[i][1]
		count = 0
		i = 0
		j = 1
		k = 2
		while k < n:
			if len(set([v[i], v[j], v[k]])) == 3:
				if 2 + f[j] < count or count == 0:
					count = 2 + f[j]
			i += 1
			j += 1
			k += 1
		print(count)


t = int(input())
for _ in range(t):
	s = input()
	n = len(s)
	if len(set(s)) != 3:
		print(0)
		continue
	start = 0
	end = 0
	one = 0
	two = 0
	three = 0
	best = 420420420
	while end < n:
		if min(one, two, three) > 0:
			best = min(best, one + two + three)
			if s[start] == '1':
				one -= 1
			elif s[start] == '2':
				two -= 1
			else:
				three -= 1
			start += 1
		else:
			if s[end] == '1':
				one += 1
			elif s[end] == '2':
				two += 1
			else:
				three += 1
			end += 1
			if min(one, two, three) > 0:
				best = min(best, one + two + three)
	if start < end and min(one, two, three) > 0:
		while min(one, two, three) != 0 and start < end:
			if s[start] == '1':
				one -= 1
			elif s[start] == '2':
				two -= 1
			else:
				three -= 1
			if min(one, two, three) > 0:
				best = min(best, one + two + three)
			start += 1
	if best == 420420420:
		print(0)
	else:
		print(best)


t = int(input())
for _ in range(t):
	s = input()
	if not ('1' in s and '2' in s and ('3' in s)):
		print(0)
		continue
	info = []
	cnt = 1
	cur = s[0]
	for c in s[1:] + '4':
		if c == cur:
			cnt += 1
		else:
			info.append((cur, cnt))
			cur = c
			cnt = 1
	out = len(s)
	for (i, tup) in enumerate(info[1:-1]):
		if tup[1] + 2 >= out:
			continue
		g = set('123')
		g.discard(tup[0])
		g.discard(info[i][0])
		g.discard(info[i + 2][0])
		if not g:
			out = min(out, tup[1] + 2)
	print(out)


from collections import Counter
for _ in range(int(input())):
	a = input()
	ma = {'1': 0, '2': 0, '3': 0}
	i = 0
	j = 0
	n = len(a)
	size = n + 1
	while j < n:
		while j < n:
			if ma['1'] >= 1 and ma['2'] >= 1 and (ma['3'] >= 1):
				size = min(size, j - i)
				break
			if a[j] in ma:
				ma[a[j]] += 1
			j += 1
		while i <= j:
			if ma['1'] < 1 or ma['2'] < 1 or ma['3'] < 1:
				size = min(size, j - i + 1)
				break
			if a[i] in ma:
				ma[a[i]] -= 1
			i += 1
	print(size if size < n + 1 else 0)


for _ in range(int(input())):
	data = input()
	result = 1000000000.0
	one = -1
	two = -1
	three = -1
	length = len(data)
	for i in range(length):
		if data[i] == '1':
			one = i
		elif data[i] == '2':
			two = i
		else:
			three = i
		if one != -1 and two != -1 and (three != -1):
			result = min(result, max([one, two, three]) - min([one, two, three]) + 1)
	if result == 1000000000.0:
		print(0)
	else:
		print(result)


t = int(input())
for uuu in range(t):
	s = [int(x) for x in input()]
	cnt = [0, -1, -1, -1]
	for i in range(len(s)):
		if cnt[s[i]] == -1:
			cnt[s[i]] = i
	if cnt[1] == -1 or cnt[2] == -1 or cnt[3] == -1:
		print(0)
		continue
	ans = len(s)
	last1 = cnt[1]
	last2 = cnt[2]
	last3 = cnt[3]
	ans = min(ans, max(last1, last2, last3) - min(last1, last2, last3) + 1)
	for i in range(len(s)):
		if s[i] == 1:
			last1 = i
		if s[i] == 2:
			last2 = i
		if s[i] == 3:
			last3 = i
		ans = min(ans, max(last1, last2, last3) - min(last1, last2, last3) + 1)
	print(ans)


from sys import stdin, stdout
import sys
import bisect

def findCloset(A, B, C, p, q, r):
	diff = sys.maxsize
	(res_i, res_j, res_k, i, j, k) = (0, 0, 0, 0, 0, 0)
	while i < p and j < q and (k < r):
		minimum = min(A[i], min(B[j], C[k]))
		maximum = max(A[i], max(B[j], C[k]))
		if maximum - minimum < diff:
			(res_i, res_j, res_k) = (i, j, k)
			diff = maximum - minimum
		if diff == 0:
			break
		if A[i] == minimum:
			i = i + 1
		elif B[j] == minimum:
			j = j + 1
		else:
			k = k + 1
	return (min(A[res_i], B[res_j], C[res_k]), max(A[res_i], B[res_j], C[res_k]))
t = int(stdin.readline())
for _ in range(t):
	s = stdin.readline().rstrip()
	a = list()
	b = list()
	c = list()
	n = len(s)
	for i in range(n):
		if s[i] == '1':
			bisect.insort(a, i)
		elif s[i] == '2':
			bisect.insort(b, i)
		else:
			bisect.insort(c, i)
	if (len(a) == 0 or len(b) == 0) or len(c) == 0:
		stdout.write('0\n')
	else:
		(j, k) = findCloset(a, b, c, len(a), len(b), len(c))
		stdout.write(str(k - j + 1) + '\n')


def single():
	return int(input())

def multiple():
	return list(map(int, input().split()))
t = single()
for i in range(t):
	a = input()
	a = list(a)
	l = len(a)
	t = '123'
	which = {i: 0 for i in t}
	for i in t:
		which[i] += 1
	s = 0
	e = 0
	temp = {i: 0 for i in which}

	def check(c, b):
		for i in c:
			if c[i] < b[i]:
				return False
		return True
	x = 100000000
	y = 10000000000
	while e < l:
		if a[e] in which:
			temp[a[e]] += 1
			while check(temp, which):
				if a[s] in temp:
					temp[a[s]] -= 1
				if y - x > e - s:
					x = s
					y = e
				s += 1
		e += 1
	print(len(a[x:y + 1]))


t = int(input())
for _ in range(t):
	s = input()
	x = 0
	y = 0
	z = 0
	l = []
	for i in range(0, len(s)):
		if s[i] == '1':
			x = i + 1
		elif s[i] == '2':
			y = i + 1
		elif s[i] == '3':
			z = i + 1
		if x > 0 and y > 0 and (z > 0):
			var = max(x, y, z)
			va1 = min(x, y, z)
			l.append(var - va1 + 1)
	if len(l) == 0:
		print(0)
	else:
		print(min(l))


from itertools import accumulate, groupby
import math
for _ in range(int(input())):
	s = input()
	S = list(s)
	A = [0]
	Ans = []
	for i in S:
		if A[-1] != i:
			A.append(i)
	res = [len(list(j)) for (_, j) in groupby(S)]
	A = A[1:]
	for i in range(1, len(A) - 1):
		if sorted(A[i - 1] + A[i] + A[i + 1]) == ['1', '2', '3']:
			Ans.append(1 + res[i] + 1)
	print(min(Ans)) if len(Ans) > 0 else print(0)


for _ in range(int(input())):
	w = input()
	a = 0
	b = 0
	c = 0
	seq = 0
	for i in range(len(w)):
		if w[i] == '1' and a < i + 1:
			a = i + 1
		elif w[i] == '2' and b < i + 1:
			b = i + 1
		elif w[i] == '3' and c < i + 1:
			c = i + 1
		if a > 0 and b > 0 and (c > 0):
			if seq == 0:
				seq = max(a, b, c) - min(a, b, c)
			else:
				seq = min(seq, max(a, b, c) - min(a, b, c))
			if a == min(a, b, c):
				a = 0
			elif b == min(a, b, c):
				b = 0
			elif c == min(a, b, c):
				c = 0
	if seq > 0:
		print(seq + 1)
	else:
		print(seq)


t = int(input())
for _ in range(t):
	s = input()
	count = [-1, -1, -1]
	ans = len(s) + 1
	for (ind, val) in enumerate(s):
		count[ord(val) - ord('1')] = ind
		ans = min(ans, max(count) - min(count) + 1) if min(count) >= 0 else ans
	print(ans if ans <= len(s) else 0)


for _ in range(int(input())):
	s = input()
	if s.count('1') == 0 or s.count('2') == 0 or s.count('3') == 0:
		print(0)
	else:
		pat = '123'
		hash_pat = [0] * 256
		hash_str = [0] * 256
		for i in range(3):
			hash_pat[ord(pat[i])] += 1
		(start, start_index, min_len) = (0, -1, float('inf'))
		count = 0
		for j in range(len(s)):
			hash_str[ord(s[j])] += 1
			if hash_pat[ord(s[j])] != 0 and hash_str[ord(s[j])] <= hash_pat[ord(s[j])]:
				count += 1
			if count == 3:
				while hash_str[ord(s[start])] > hash_pat[ord(s[start])] or hash_pat[ord(s[start])] == 0:
					if hash_str[ord(s[start])] > hash_pat[ord(s[start])]:
						hash_str[ord(s[start])] -= 1
					start += 1
				len_window = j - start + 1
				if min_len > len_window:
					min_len = len_window
					start_index = start
		print(min_len)