Problem:


Score : 300 points

Problem Statement

Snuke can change a string t of length N into a string t' of length N - 1 under the following rule:

For each i (1 ≤ i ≤ N - 1), the i-th character of t' must be either the i-th or (i + 1)-th character of t.

There is a string s consisting of lowercase English letters.
Snuke's objective is to apply the above operation to s repeatedly so that all the characters in s are the same.
Find the minimum necessary number of operations.

Constraints

1 ≤ |s| ≤ 100

s consists of lowercase English letters.

Input

Input is given from Standard Input in the following format:

s

Output

Print the minimum necessary number of operations to achieve the objective.

Sample Input 1

serval

Sample Output 1

3

One solution is: serval → srvvl → svvv → vvv.

Sample Input 2

jackal

Sample Output 2

2

One solution is: jackal → aacaa → aaaa.

Sample Input 3

zzz

Sample Output 3

0

All the characters in s are the same from the beginning.

Sample Input 4

whbrjpjyhsrywlqjxdbrbaomnw

Sample Output 4

8

In 8 operations, he can change s to rrrrrrrrrrrrrrrrrr.



Sample input:
serval


Sample output:
3

Submission status: Accepted

Solution code:
import copy
s = input()
n = len(s)
l = []
c = [0]*26

for i in s:
    l.append(ord(i)-ord("a"))
    c[l[-1]] += 1

ans = 10**10

for i in range(26):
    if c[i]:
        count = 0
        l2 = copy.deepcopy(l)
        while (n-count)*i != sum(l2):
            count += 1
            nl = []
            for j in range(n-count):
                if l2[j] == i or l2[j+1] == i:
                    nl.append(i)
                else:
                    nl.append(1000)
            l2 = nl
        ans = min(ans,count)
print(ans)

Submission status: Accepted

Solution code:
s = input()
min_change = 100
for char in 'abcdefghijklmnopqrstuvwxyz':
    absence = 0
    max_absence = 0
    for i in s:
        if i != char:
            absence += 1
        else:
            max_absence = max(max_absence,absence)
            absence = 0
    max_absence = max(max_absence,absence)
    min_change = min(min_change,max_absence)
print(min_change)

Submission status: Accepted

Solution code:
s = input()
l = {}
for i in s:
    l.setdefault(i, 0)
    l[i] += 1
ans = float("inf")
for i in l.keys():
    count = 0
    s0 = ""
    for j in s:
        if i == j:
            s0 += i
        else:
            s0 += "."
    while "." in s0:
        count += 1
        s1 = ""
        for j in range(len(s0) - 1):
            if s0[j] == i or s0[j + 1] == i:
                s1 += i
            else:
                s1 += "."
        s0 = s1
    else:
        ans = min(ans, count)
print(ans)

Submission status: Accepted

Solution code:
s = input()
ss = set(s)
# print(ss)
ans = float('inf')
for si in ss:
    cnt = 0
    copy_s = list(s)
    # print(copy_s)
    while len(set(copy_s)) != 1:
        # copy_s.pop()
        cnt += 1
        for i in range(len(copy_s)-1):
            if copy_s[i+1] == si:
                copy_s[i] = si
        copy_s.pop()
    ans = min(ans, cnt)

print(ans)

Submission status: Accepted

Solution code:
import sys
import math
import copy
import heapq
from functools import cmp_to_key
from bisect import bisect_left, bisect_right
from collections import defaultdict, deque, Counter
# sys.setrecursionlimit(1000000)

# input aliases
input = sys.stdin.readline
getS = lambda: input().strip()
getN = lambda: int(input())
getList = lambda: list(map(int, input().split()))
getZList = lambda: [int(x) - 1 for x in input().split()]

INF = float("inf")
MOD = 10**9 + 7
divide = lambda x: pow(x, MOD-2, MOD)

def nck(n, k, kaijyo):
    return (npk(n, k, kaijyo) * divide(kaijyo[k])) % MOD

def npk(n, k, kaijyo):
    if k == 0 or k == n:
        return n % MOD
    return (kaijyo[n] * divide(kaijyo[n-k])) % MOD

def fact_and_inv(SIZE):
    inv = [0] * SIZE  # inv[j] = j^{-1} mod MOD
    fac = [0] * SIZE  # fac[j] = j! mod MOD
    finv = [0] * SIZE  # finv[j] = (j!)^{-1} mod MOD
    inv[1] = 1
    fac[0] = fac[1] = 1
    finv[0] = finv[1] = 1
    for i in range(2, SIZE):
        inv[i] = MOD - (MOD // i) * inv[MOD % i] % MOD
        fac[i] = fac[i - 1] * i % MOD
        finv[i] = finv[i - 1] * inv[i] % MOD

    return fac, finv

def renritsu(A, Y):
    # example 2x + y = 3, x + 3y = 4
    # A = [[2,1], [1,3]])
    # Y = [[3],[4]] または [3,4]
    A = np.matrix(A)
    Y = np.matrix(Y)
    Y = np.reshape(Y, (-1, 1))
    X = np.linalg.solve(A, Y)

    # [1.0, 1.0]
    return X.flatten().tolist()[0]

class TwoDimGrid:
    # 2次元座標 -> 1次元
    def __init__(self, h, w, wall="#"):
        self.h = h
        self.w = w
        self.size = (h+2) * (w+2)
        self.wall = wall
        self.get_grid()
        # self.init_cost()

    def get_grid(self):
        grid = [self.wall * (self.w + 2)]
        for i in range(self.h):
            grid.append(self.wall + getS() + self.wall)

        grid.append(self.wall * (self.w + 2))
        self.grid = grid
    def init_cost(self):
        self.cost = [INF] * self.size

    def pos(self, x, y):
        # 壁も含めて0-indexed 元々の座標だけ考えると1-indexed
        return y * (self.w + 2) + x
    def getgrid(self, x, y):
        return self.grid[y][x]
    def get(self, x, y):
        return self.cost[self.pos(x, y)]
    def set(self, x, y, v):
        self.cost[self.pos(x, y)] = v
        return
    def show(self):
        for i in range(self.h+2):
            print(self.cost[(self.w + 2) * i:(self.w + 2) * (i+1)])
    def showsome(self, tgt):
        for t in tgt:
            print(t)
        return
    def showsomejoin(self, tgt):
        for t in tgt:
            print("".join(t))
        return

    def search(self):
        grid = self.grid
        move = [(0, 1), (0, -1), (1, 0), (-1, 0)]
        move_eight = [(0, 1), (0, -1), (1, 0), (-1, 0), (1, 1), (1, -1), (-1, 1), (-1, -1)]
        # for i in range(1, self.h+1):
        #     for j in range(1, self.w+1):
        #         cx, cy = j, i
        #         for dx, dy in move_eight:
        #             nx, ny = dx + cx, dy + cy

def judge(id, sho, n):
    hito = [0]
    for i in range(n):
        if id % 2 == 1:
            hito.append(1)
        else:
            hito.append(0)
        id //= 2

    for i, h in enumerate(hito):
        if i == 0:
            continue
        if h == 1:
            for x, y in sho[i-1]:
                if hito[x] != y:
                    return -1

    return sum(hito)


def solve():
    S = getS()
    ans = INF
    for i in range(26):
        tgt = chr(ord("a") + i)
        prev = ""
        tmp = 0
        ttmp = 0
        for c in S:
            if c == tgt:
                tmp = max(tmp, ttmp)
                ttmp = 0
            else:
                ttmp += 1
        tmp = max(tmp, ttmp)
        ans = min(ans, tmp)

    print(ans)



def main():
    n = getN()
    for _ in range(n):
        solve()

    return
if __name__ == "__main__":
    # main()
    solve()

Submission status: Accepted

Solution code:
s = input()
indices = {}

for i in range(len(s)):
    if s[i] in indices:
        indices[s[i]].append(i)
    else:
        indices[s[i]] = [-1, i]

minres = 1000

for key, value in indices.items():
    if len(value) > 1:
        dist = [value[i+1]-value[i] - 1 for i in range(len(value) - 1)]
    else:
        dist = [value[0]]

    res = max(max(dist), len(s)-value[-1]-1)
    if res < minres:
        minres = res

print(minres)

Submission status: Accepted

Solution code:
S = list(input())
N = len(S)
D = {}
for i in range(N):
    D[S[i]] = D.get(S[i],[-1])
    D[S[i]].append(i)
out = 100
for L in D.values():
    L.append(N)
    LN = len(L)
    tmp = 0
    for i in range(LN-1):
        tmp = max(tmp, L[i+1]-L[i]-1)
    out=min(out,tmp)
print(out)

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10 ** 9)
# input = sys.stdin.readline    ####
def int1(x): return int(x) - 1
def II(): return int(input())
def MI(): return map(int, input().split())
def MI1(): return map(int1, input().split())
def LI(): return list(map(int, input().split()))
def LI1(): return list(map(int1, input().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def MS(): return input().split()
def LS(): return list(input())
def LLS(rows_number): return [LS() for _ in range(rows_number)]
def printlist(lst, k=' '): print(k.join(list(map(str, lst))))
INF = float('inf')
# from math import ceil, floor, log2
from collections import deque, defaultdict
# from itertools import combinations as comb, combinations_with_replacement as comb_w, accumulate, product, permutations
# from heapq import heapify, heappop, heappush
# import numpy as np    # cumsum
# from bisect import bisect_left, bisect_right

def solve():
    S = LS()
    d = defaultdict(lambda: 0)
    # print(len(S))
    for s in S:
        d[s] += 1
    # print(d)
    ans = INF
    for c, n in d.items():
        cnt = 0
        mx = 0
        for s in S:
            if c == s:
                mx = max(mx, cnt)
                cnt = 0
                continue
            cnt += 1
        mx = max(mx, cnt)
        # print(c, mx)
        ans = min(ans, mx)
    print(ans)

if __name__ == '__main__':
    solve()

Submission status: Accepted

Solution code:
from collections import defaultdict


def main():
    S = input()
    N = len(S)
    index_list_dict = defaultdict(list)
    for i, c in enumerate(S):
        index_list_dict[c].append(i)
    ans = N
    for index_list in index_list_dict.values():
        li = [-1] + index_list + [N]
        v = 0
        for i in range(len(li) - 1):
            v = max(v, li[i + 1] - li[i] - 1)
        ans = min(ans, v)
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
s = str(input())
n = len(s)
x = "abcdefghijklmnopqrstuvwxyz"
mn = 101
for i in range(26):
  t = x[i]
  mx = 0
  c = 0
  for j in range(n):
    if s[j] == t:
      if mx < c:
        mx = c
      c = 0
    else:
      c += 1
  if mx < c:
    mx = c
  if mx < mn:
    mn = mx
print(mn)

Submission status: Accepted

Solution code:
# 出現回数が最大の文字に統一することが最小値とは限らないので全ての文字列でシミュレーションする

S = input()

ans = 100
for s in S:
    s_split = S.split(s)
    max_len = 0
    for i in range(len(s_split)):
        max_len = max(max_len, len(s_split[i]))
    ans = min(ans, max_len)
print(ans)

Submission status: Accepted

Solution code:
import copy

s = input()
n = len(s)

ans = 10**10

if len(set(list(s))) == 1:
    print(0)
    exit()

for i in range(26):
    t = chr(i + ord('a'))
    tmp = 0
    li = [False] * n
    for j in range(n):
        if s[j] == t:
            li[j] = True
    while True:
        li_tmp = [False] * (n - tmp - 1)
        for j in range(n-tmp):
            if li[j]:
                if j > 0:
                    li_tmp[j-1] = True
                if j < n-tmp-1:
                    li_tmp[j] = True
        tmp += 1
        if all(li_tmp):
            ans = min(ans, tmp)
            break
        else:
            li = copy.copy(li_tmp)

print(ans)

Submission status: Accepted

Solution code:
s = input()
l = len(s)

c = set([])
for x in s:
    c.add(x)

def solve(arg):
    res = 0
    id = -1
    for i in range(l):
        if s[i] == arg:
            if res < i - id - 1:
                res = i - id - 1
            id = i
    if l - id - 1 > res:
        res = l - id - 1
    return res

ans = 1001001
for x in c:
    tmp = solve(x)
    if tmp < ans:
        ans = tmp

print(ans)

Submission status: Accepted

Solution code:
S = input()

ans = 100
for s in S:
    S_split = S.split(s)
    max_len = 0
    for i in range(len(S_split)):
        max_len = max(max_len, len(S_split[i]))
    ans = min(ans, max_len)

print(ans)

Submission status: Accepted

Solution code:
import collections
s = input()
a = []
for i in range(26):
    cnt = collections.Counter(s)[chr(i+97)]
    if cnt == 0:
        a.append(len(s))
        continue
    num = 0
    ma = 0
    for j in s:
        if j == chr(i+97):
            ans = num
            ma = max(ma, ans)
            num = 0
        else:
            num += 1
        ans = num
        ma = max(ma, ans)
    a.append(ma)
print(min(a))

Submission status: Accepted

Solution code:
s=input()
l=len(s)
ans=101
if len(set(s))==1:
    print(0)
    exit()
for target in s:
    a=s
    for i in range(l):
        tmp=[]
        for j in range(l-i-1):
            if a[j]==target or a[j+1]==target:
                tmp.append(target)
            else:
                tmp.append(a[j])
        a=tmp
        if len(set(a))==1:
            ans=min(ans,i+1)
            break
print(ans)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3

# from numba import njit

# from collections import Counter
# from itertools import accumulate
# import numpy as np
# from heapq import heappop,heappush
# from bisect import bisect_left

INF = pow(10,5)

def countProcedure(lst,char,cnt=0):
  flags = [x == char for x in lst]
  if all(flags):
    return cnt
  else:
    lst = [char if lst[i] == char or lst[i+1] == char else lst[i] for i in range(len(lst)-1)]
    return countProcedure(lst,char,cnt+1)

# @njit
def solve(s):
  s = list(s)
  res = INF
  for char in (chr(ord("a") + i) for i in range(26)):
    res = min(res,countProcedure(s,char))

  return res



def main():
  s = input()
  print(solve(s))
  return

if __name__ == '__main__':
  main()

Submission status: Accepted

Solution code:
#!/usr/bin/env python3

# from numba import njit

# from collections import Counter
# from itertools import accumulate
# import numpy as np
# from heapq import heappop,heappush
# from bisect import bisect_left

INF = pow(10,5)

def countProcedure(lst,char,cnt=0):
  flags = [x == char for x in lst]
  if all(flags):
    return cnt
  else:
    _lst = [char if lst[i] == char or lst[i+1] == char else lst[i] for i in range(len(lst)-1)]
    return countProcedure(_lst,char,cnt+1)

# @njit
def solve(s):
  s = list(s)
  res = INF
  for char in (chr(ord("a") + i) for i in range(26)):
    res = min(res,countProcedure(s,char))

  return res



def main():
  s = input()
  print(solve(s))
  return

if __name__ == '__main__':
  main()

Submission status: Accepted

Solution code:
import collections
s = input()
sl = collections.Counter(s)
ans = len(s)
s_af = s
for c in sl.keys():
    s_af = s
    cnt = 0
    while s_af.count(c) != len(s_af):
        s_bf = s_af
        cnt +=1
        for i in range(len(s_bf)-1):
            if s_bf[i] ==c or s_bf[i+1]==c:
                if i ==0:
                    s_af = c
                else:
                    s_af += c
            else:
                if i == 0:
                    s_af = s_bf[i]
                else:
                    s_af += s_bf[i]
    ans = min(ans,cnt)

    
print(ans)

Submission status: Accepted

Solution code:
s = input()
print(min(max(map(len, s.split(a))) for a in s))

Submission status: Accepted

Solution code:
import copy
s = list(input())

anslst = []
lst = copy.deepcopy(s)

for x in lst:
    ss = copy.deepcopy(s)
    n = len(ss)
    cnt = 0
    while True:
        tmp = ss[0]
        flg = 0
        for moji in ss:
            if moji != tmp:
                flg = 1
        if flg == 0:
            anslst.append(cnt)
            break

        for i in range(1, n):
            if ss[i - 1] == x or ss[i] == x:
                ss[i - 1] = x
        ss.pop()
        n = len(ss)
        cnt += 1
print(min(anslst))

Submission status: Accepted

Solution code:
import string

s = input()
alps = string.ascii_lowercase
mx = {c:0 for c in alps}
tmp = {c:0 for c in alps}

for char in s:
    for alp in alps:
        if alp == char:
            mx[alp] = max(mx[alp], tmp[alp])
            tmp[alp] = 0
        else:
            tmp[alp] += 1

for alp in alps:
    mx[alp] = max(mx[alp], tmp[alp])

print(min(mx.values()))

Submission status: Accepted

Solution code:
s = input()
n = len(s)
ans = float("Inf")
for i in range(n):
    x = s[i]
    t = list(s)
    c = 0
    for j in range(n-1):
        if t.count(x) == len(t):
            break
        for k in range(len(t)-1):
            if t[k+1] == x:
                t[k] = x
        c += 1
        t = t[:len(t)-1]
    ans = min(ans, c)
print(ans)

Submission status: Accepted

Solution code:
S=list(input())
N=len(S)
ans=100

for s in S:
    i=0
    C=0
    count2=0
    while i<N:
        if s!=S[i]:
            count2+=1
        else:
            C=max(C,count2)
            count2=0
        i+=1
    C=max(C,count2)
    ans=min(C,ans)

print(ans)

Submission status: Accepted

Solution code:
import sys

readline = sys.stdin.readline
MOD = 10 ** 9 + 7
INF = float('INF')
sys.setrecursionlimit(10 ** 5)


def main():
    s = input()
    chars = list(set(s))
    ans = INF

    for char in chars:
        t = s[:]
        cnt = 0
        while True:
            if len(set(t)) == 1:
                ans = min(ans, cnt)
                break
            l = len(t)
            r = ""
            for i in range(l - 1):
                if t[i] == char or t[i + 1] == char:
                    r += char
                else:
                    r += t[i]
            cnt += 1
            t = r

    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
from collections import Counter

s = input()
ans = 100
cs = set(i for i in s)
for c in cs:
    a = 0
    ns = s
    while ns.count(c) < len(ns):
        nns = ""
        for i in range(len(ns) - 1):
            if c in (ns[i], ns[i + 1]):
                nns += c
            else:
                nns += ns[i]
        ns = nns
        a += 1
    ans = min(a, ans)
print(ans)

Submission status: Accepted

Solution code:
def getN():
    return int(input())
def getNM():
    return map(int, input().split())
def getList():
    return list(map(int, input().split()))
def getArray(intn):
    return [int(input()) for i in range(intn)]
def input():
    return sys.stdin.readline().rstrip()
def rand_N(ran1, ran2):
    return random.randint(ran1, ran2)
def rand_List(ran1, ran2, rantime):
    return [random.randint(ran1, ran2) for i in range(rantime)]
def rand_ints_nodup(ran1, ran2, rantime):
  ns = []
  while len(ns) < rantime:
    n = random.randint(ran1, ran2)
    if not n in ns:
      ns.append(n)
  return sorted(ns)

def rand_query(ran1, ran2, rantime):
  r_query = []
  while len(r_query) < rantime:
    n_q = rand_ints_nodup(ran1, ran2, 2)
    if not n_q in r_query:
      r_query.append(n_q)
  return sorted(r_query)

from collections import defaultdict, deque, Counter
from sys import exit
from decimal import *
import heapq
from math import sqrt
from fractions import gcd
import random
import string
import copy
from itertools import combinations, permutations, product
from operator import mul, itemgetter
from functools import reduce
from bisect import bisect_left, bisect_right

import sys
sys.setrecursionlimit(1000000000)
mod = 10 ** 9 + 7

#############
# Main Code #
#############

S = input()
N = len(S)

dict = defaultdict(list)

for i in range(N):
    dict[S[i]].append(i)

ans = float('inf')
for key, value in dict.items():
    value.insert(0, -1)
    value.append(N)

    length = 0
    for j in range(len(value) - 1):
        length = max(length, value[j + 1] - value[j])
    ans = min(ans, length)
print(ans - 1)

Submission status: Accepted

Solution code:
import bisect, collections, copy, heapq, itertools, math, string, sys
input = lambda: sys.stdin.readline().rstrip() 
sys.setrecursionlimit(10**7)
INF = float('inf')
def I(): return int(input())
def F(): return float(input())
def SS(): return input()
def LI(): return [int(x) for x in input().split()]
def LI_(): return [int(x)-1 for x in input().split()]
def LF(): return [float(x) for x in input().split()]
def LSS(): return input().split()

def resolve():
    s = SS()

    # 文字同士のindexの隙間の最大値の最小値

    len_s = len(s)

    # 文字毎のindex
    idx = [[] for _ in range(26)]
    for i in range(len_s):
        idx[ord(s[i]) - ord('a')].append(i)

    # 文字毎のindexの間の文字数
    idx_gap = [[] for _ in range(26)]
    for i in range(26):
        if len(idx[i]) >= 1:
            idx_gap[i].append(idx[i][0])
            idx_gap[i].append(len_s - idx[i][-1] - 1)
            if len(idx[i]) >= 2:
                for j in range(len(idx[i]) - 1):
                    idx_gap[i].append(idx[i][j+1] - idx[i][j] - 1)

    print(min([max(i) for i in idx_gap if i]))

if __name__ == '__main__':
    resolve()

Submission status: Accepted

Solution code:
s = input()

ans = 10**13
for si in s:
    t = s
    for j in range(len(t)):
        tt = ''
        if len(set(t)) == 1:
            ans = min(ans, j)
            break
        for k in range(len(s)-j-1):
            if t[k] == si or t[k+1] == si:
                tt += si
            else:
                tt += '*'
        t = tt

print(ans)

Submission status: Accepted

Solution code:
s = input()
N = len(s)
res = N
for i in range(26):
    j = 0
    t = 0
    while j < N:
        cnt = 0
        while j < N and s[j] == chr(i + ord('a')):
            j += 1
        while j < N and s[j] != chr(i + ord('a')):
            cnt += 1
            j += 1
        t = max(t, cnt)
    res = min(res, t)
print(res)

Submission status: Accepted

Solution code:
from collections import Counter
s = list(input())
d =  Counter(s)
key = d.keys()
ans = len(s)//2 + len(s)%2
for k in key:
    ck = 0
    i = 0
    while True:
        if s[i] == k:
            i += 1
            if i == len(s):
                break
        else:
            cnt = 0
            while s[i + cnt] != k:
                cnt += 1
                if i + cnt == len(s):
                    break
            ck = max(ck, cnt)
            i += cnt
            if i == len(s):
                break
    ans = min(ans, ck)
print(ans)

Submission status: Accepted

Solution code:
# https://atcoder.jp/contests/agc016/tasks/agc016_a
# 真ん中らへんの文字を採用すれば結構早く同じ文字になる
# 最終的にどの文字にしたいかターゲットを絞って、操作するのを繰り返せば？(100*100*答え回の探索ですむ)
from collections import Counter
S = input()
cnt = Counter(S)
ans = 10**5
for k in cnt:
    # cnt_k = cnt[k]  # 個数管理用
    ans_k = 0
    T = list(S)
    # print(cnt_k)
    while not all([t == k for t in T]):
        ans_k += 1
        new_T = []
        for i in range(len(T) - 1):
            if T[i] == k:
                new_T.append(k)
            elif T[i + 1] == k:
                new_T.append(k)
            else:
                new_T.append(T[i])
        T = new_T
    # print(T, cnt_k)
    ans = min(ans, ans_k)
print(ans)

Submission status: Accepted

Solution code:
S=input()
N=len(S)
Z={}

for i in range(N):
    if S[i] in Z:
        Z[S[i]].append(i)
    else:
        Z[S[i]]=[i]
    
M=float("inf")
for z in Z:
    L=[1*(i in Z[z]) for i in range(N)]

    K=0
    while sum(L)!=len(L):
        K+=1
        for i in range(len(L)-1):
            L[i]=max(L[i],L[i+1])
        L=L[:-1]
    
    M=min(M,K)
print(M)

Submission status: Accepted

Solution code:
s=input()
an=[]
for m in "qwertyuiopasdfghjklzxcvbnm":
  i=0
  d=[len(s)-j for j in range(len(s))]
  while s.find(m,i)>=0:
    t=s.find(m,i)
    for j in range(t+1):
      d[j]=min(t-j,d[j])
    i=t+1

  mi=0
  for i in range(len(s)):
    mi=max(mi,d[i])
  an.append(max(d))
print(min(an))

Submission status: Accepted

Solution code:
s=[s for s in input()]
alp=[chr(ord('a')+i) for i in range(26)]
n=len(s)
ans=10**9
for a in alp:
  t=s
  if not a in s:continue
  for i in range(n):
    if len(set(t))==1:break
    b=[]
    for j in range(n-i-1):
      if t[j]==a:b+=[t[j]]
      elif t[j+1]==a:b+=t[j+1]
      else:b+=t[j]
    t=b
  ans=min(ans,i)
print(ans)

Submission status: Accepted

Solution code:
from string import ascii_lowercase
from collections import Counter

def main():
    S = input()
    N = len(S)
    ans = 100
    c = Counter(list(S))

    if any(val == N for  val in c.values()):
        print(0)
        exit()


    for letter in ascii_lowercase:
        count = 0
        T = S
        while True:
            count += 1
            flag = True
            n = len(T)
            next_T = ""

            for i in range(n-1):
                if letter in T[i:i+2]:
                    next_T += letter
                else:
                    next_T += "#"
                    flag = False

            if flag:
                break
            T = next_T
        ans = min(ans, count)

    print(ans)

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
enum = enumerate

import collections
import random

def linput(ty=int, cvt=list):
	return cvt(map(ty,input().split()))

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

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

def dist(x1,y1,x2,y2):
	return abs(x1-x2)+abs(y1-y2)

def main():
	S = input().rstrip()
	#vS = [input().rstrip() for _ in [0,]*N]
	N = len(S)
	oA = ord("a")
	vD = [chr(i+oA) for i in range(26)]
	#vD += [".","#"]

	res = 0
	M = N
	
	# dp[i..M][d..26] = y/n
	vN = [[0,]*26 for _ in "*"*M]

	for i,s in enum(S):
		d = ord(s)-oA
		vN[i][d] = 1

	while M:
		ok = 0
		for d in range(26):
			for i in range(M):
				if not vN[i][d]: break
			else:
				ok = 1; break
		if ok: break
		M -= 1
		for d in range(26):
			for i in range(M):
				vN[i][d] |= vN[i+1][d]
	
	res = N - M
	print(res)
	#sT = "No Yes".split()
	#print(sT[res])
	

if __name__ == "__main__":
	main()

Submission status: Accepted

Solution code:
S=input()
d=[[-1,len(S)] for i in range(26)]
for i,s in enumerate(S):
    d[ord(s)-ord('a')].insert(-1,i)
print(min([max([l[i+1]-l[i]-1 for i in range(len(l)-1)]) for l in d]))

Submission status: Accepted

Solution code:
N=input()
import collections
tmp=list(collections.Counter(N).keys())
ans=float("Inf")
import copy
for i in tmp:
   c=0
   l=copy.deepcopy(N)
   while len(set(l))!=1:
      tmp2=[]
      for j in range(len(l)-1):
         if l[j] ==i or l[j+1]==i:
            tmp2.append(i)
         else:
            tmp2.append(l[j])
      c+=1
      l=copy.deepcopy(tmp2)
   ans=min(ans,c)
print(ans)

Submission status: Accepted

Solution code:
def find_idx(s, c):
  idx_lst = [len(i) for i in s.split(c)]
  return idx_lst

s = input()
res = float('inf')
for i in range(97, 97 + 26):
  tmp = find_idx(s, chr(i))
  if tmp:
    res = min(res, max(tmp))
print(res)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
import sys
from collections import deque, defaultdict
from math import sqrt, factorial, gcd
# def input(): return sys.stdin.readline()[:-1] # warning not \n
# def input(): return sys.stdin.buffer.readline().strip() # warning bytes
# def input(): return sys.stdin.buffer.readline().decode('utf-8')


def solve():
    s = input()
    chars = set([x for x in s])
    mn = len(s)
    for c in chars:
        mx = max([len(x) for x in s.split(c)])
        mn = min(mn, mx)
    print(mn)
    



t = 1
# t = int(input())
for case in range(1,t+1):
    ans = solve()


"""



"""

Submission status: Accepted

Solution code:
from copy import deepcopy
ss=list(input())
ans=float("inf")
n=len(ss)
for i in range(n):
    s=deepcopy(ss)
    t=ss[i]
    flg=True
    while flg:
        tmp=""
        if all(s[k]==t for k in range(len(s))):
            tt=len(ss)-len(s)
            if tt<ans:
                ans=tt
            flg=False
            break
        for j in range(len(s)-1):
            
            if s[j]==t or s[j+1]==t:
                tmp+=t
            else:
                tmp+=s[j]
        s=tmp
print(ans)

Submission status: Accepted

Solution code:
import copy
import string

s = list(input())
ans = 0
if len(set(s)) == 1:
  print(0)
else:
  for k in string.ascii_lowercase:
    tmp = 0
    l = copy.deepcopy(s)
    while any(ss != k for ss in l):
      for i in range(len(l) - 1):
        if l[i + 1] == k:
          l[i] = k
      l.pop(-1)
      tmp += 1
    if ans:
      ans = min(ans, tmp)
    else:
      ans = tmp
  print(ans)

Submission status: Accepted

Solution code:
from string import ascii_lowercase

S = list(input())

ans = 10 ** 18
# 全てのアルファベットを試す
for moji in ascii_lowercase:
    tmp = S[:]
    count = 0
    while len(set(list(tmp))) != 1:
        for i in range(len(tmp) - 1):
            if tmp[i] == moji or tmp[i + 1] == moji:
                tmp[i] = moji
        tmp = tmp[:-1]
        count += 1
    ans = min(ans, count)
print(ans)

Submission status: Accepted

Solution code:
import sys
from collections import defaultdict
sys.setrecursionlimit(10 ** 8)
INF = float('inf')
MOD = 10 ** 9 + 7

def main():
    S = input()
    L = len(S)
    d = defaultdict(list)

    i = 0
    for s in S:
        d[s].append(i)
        i += 1

    ans = INF

    for indexs in d.values():
        last = -1
        result = 0
        for i in indexs:
            tmp = i - last - 1
            result = max(result, tmp)
            last = i
        result = max(result,L-last-1)
        ans = min(ans, result)

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


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import accumulate, permutations, combinations, product
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left
from fractions import gcd
from heapq import heappush, heappop
from functools import reduce
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7

s = input()
ans = INF
for x in set(s):
	ans = min(ans, max([len(l) for l in s.split(x)]))

print(ans)

Submission status: Accepted

Solution code:
def resolve():
    s = input()
    dict = {}
    k = 0
    for i in s:
        if i in dict:
            dict[i].append(k)
        else:
            dict[i] =[k]
        k += 1

    ans = 10**3
    for i in dict:
        test = dict[i]
        ans1 = test[0]
        for j in range(1,len(test)):
            ans1 = max(ans1, test[j]-test[j-1]-1)
        ans1 = max(ans1, (len(s)-test[-1]-1))
        ans = min(ans1,ans)
    print(ans)
resolve()

Submission status: Accepted

Solution code:
import sys
import itertools
import copy

read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline

in_n = lambda: int(readline())
in_nn = lambda: map(int, readline().split())
in_nl = lambda: list(map(int, readline().split()))
in_na = lambda: map(int, read().split())
in_s = lambda: readline().rstrip().decode('utf-8')


def main():
    s = list(in_s())[::-1]
    ss = sorted(list(set(s)))

    ans = 100
    for c in ss:
        count = 0
        ts = [c if t == c else 'A' for t in s]
        gr = itertools.groupby(ts)
        for k, v in gr:
            n = len(list(v))
            if k != c:
                count = max(count, n)
        ans = min(ans, count)

    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline

s = input()[:-1]
ans = 10**18

for a in 'abcdefghijklmnopqrstuvwxyz':
    t = s
    cnt = 0
    
    while t!=a*len(t):
        nt = ''
        
        for i in range(len(t)-1):
            if t[i]==a or t[i+1]==a:
                nt += a
            else:
                nt += t[i]
        
        t = nt
        cnt += 1
    
    ans = min(ans, cnt)

print(ans)