Problem:
 Score : 500 points    Problem Statement Given are two strings s and t consisting of lowercase English letters. Determine if there exists an integer i satisfying the following condition, and find the minimum such i if it exists.   Let s' be the concatenation of 10^{100} copies of s . t is a subsequence of the string {s'}_1{s'}_2\ldots{s'}_i (the first i characters in s' ).       Notes  A subsequence of a string a is a string obtained by deleting zero or more characters from a and concatenating the remaining characters without changing the relative order. For example, the subsequences of contest include net , c , and contest .       Constraints  1 \leq |s| \leq 10^5  1 \leq |t| \leq 10^5  s and t consists of lowercase English letters.         Input Input is given from Standard Input in the following format:  s  t       Output If there exists an integer i satisfying the following condition, print the minimum such i ; otherwise, print -1 .        Sample Input 1 contest
son      Sample Output 1 10  t =  son is a subsequence of the string contestcon (the first 10 characters in s' =  contestcontestcontest... ), so i = 10 satisfies the condition.  On the other hand, t is not a subsequence of the string contestco (the first 9 characters in s' ), so i = 9 does not satisfy the condition.  Similarly, any integer less than 9 does not satisfy the condition, either. Thus, the minimum integer i satisfying the condition is 10 .       Sample Input 2 contest
programming      Sample Output 2 -1  t =  programming is not a substring of s' =  contestcontestcontest... . Thus, there is no integer i satisfying the condition.       Sample Input 3 contest
sentence      Sample Output 3 33  Note that the answer may not fit into a 32 -bit integer type, though we cannot put such a case here.

Solution (Python):
import collections
import bisect
S = input()
T = input()
N = len(S)

d = collections.defaultdict(list)
for i, s in enumerate(S):
    d[s].append(i + 1)

ans = 0
end = 0
isOK = True
i = 0

for t in T:
    if len(d[t]) == 0:
        isOK = False
        break
    dic = d[t]
    idx = bisect.bisect_right(dic, i)
    if len(dic) == idx:
        i = dic[0]
        end += 1
    else:
        i = dic[idx]

if isOK:
    ans = N * end + i
else:
    ans = -1

print(ans)

Solution (Python):
sl = list(input())
tl = list(input())

n = len(sl)
from collections import defaultdict
dic = defaultdict(list) 

for idx, s in enumerate(sl):
   dic[s].append(idx)
   dic[s].append(idx+n)

for s in dic:
   dic[s] = sorted(dic[s])

import bisect

ans = 0
now = -1
for t in tl:
   if dic[t] == []:
      print(-1)
      import sys
      sys.exit()
   idx = bisect.bisect_left(dic[t], now+1)
   ans += dic[t][idx] - now
   now = dic[t][idx]
   if now >= n:
      now -= n
print(ans)

Solution (Python):

import bisect

s=input()
t=input()


alp=[[] for i in range(26)]

for i in range(len(s)):
    alp[ord(s[i])-ord("a")].append(i)


def bi_search(now,w):
    r=0
    if now>=alp[w][-1]:
        now=-1
        r=1
    ne_i=bisect.bisect_right(alp[w],now)
    ne=alp[w][ne_i]
    return ne,r

    
ans=0
rep=0
now=-1
for i in range(len(t)):
    num=ord(t[i])-ord("a")
    if len(alp[num])==0:
        ans=-1
        break
    now,r=bi_search(now,num)
    rep+=r
if ans==-1:
    print(ans)
else:
    ans=rep*len(s)+now+1
    print(ans)

Solution (Python):
from collections import defaultdict
import bisect

d=defaultdict(list)

s=input()
t=input()

ns=len(s)
nt=len(t)

for i in range(ns):
  d[s[i]].append(i)

for k,v in d.items():
  d[k].append(ns)


ans=0
cnt=-1

for i in range(nt):
  tt=d[t[i]]

  if tt==[]:
    print(-1)
    exit(0)
  else:
    a=bisect.bisect_right(tt,cnt)

    if tt[a]==ns:
      ans+=ns+tt[0]-cnt
      cnt=tt[0]
    else:
      ans+=tt[a]-cnt
      cnt=tt[a]
      
print(ans)

Solution (Python):
import bisect

S = input()
T = input()

ls = len(S)
d = {}
for i, s in enumerate(S):
  if s in d:
    d[s].append(i+1)
  else:
    d[s] = [i+1]


now = 0
ans = 0
pre_t = ''
for t in T:
  if not t in d:
    ans = -1
    break
    
  if t == pre_t:
    idx = bisect.bisect_left(d[t], now+1)
  else:
    idx = bisect.bisect_left(d[t], now)

  if idx == len(d[t]):
    idx = 0
  
  if d[t][idx] > now:
    ans += d[t][idx] - now
  else:
    ans += ls + d[t][idx] - now
  
  now = d[t][idx]
  pre_t = t

print(ans)

Solution (Python):
s = input()
t = input()

pos = 0
itr = 0

S = set(s)
T = set(t)

if S>=T:
    for i in t:
        pos = s.find(i,pos) 
        if pos < 0:
            itr += 1
            pos = s.find(i) + 1
        else:
            pos += 1
    print(itr*len(s)+pos)

else:
    print(-1)

Solution (Python):
s=input()
t=input()

if len(set(t)-set(s))>0:
  print(-1)
else:
  s2=s*2
  s2pos={}
  for i in range(len(s2)):
    if s2[i] in s2pos:
      s2pos[s2[i]].append(i)
    else:
      s2pos[s2[i]]=[i]

  cur=-1
  import bisect
  rev=0
  for c in t:
    cur+=1
    pos=s2pos[c]
    p=bisect.bisect_left(pos,cur)
    cur=pos[p]
    if cur>=len(s):
      cur-=len(s)
      rev+=1
  else:
    print(rev*len(s)+cur+1)

Solution (Python):
s=input()
t=input()
if len(set(t)-set(s))>0:
  print(-1)
  exit(0)

ss=s*2
ind=-1
turn=0
for c in t:
  nex=ss[ind+1:].find(c)
  ind=(ind+1)+nex
  if ind>=len(s):
    ind-=len(s)
    turn+=1

print(turn*len(s)+ind+1)

Solution (Python):
import bisect
from collections import defaultdict
s = input()
t = input()

D = defaultdict(list)
for i, c in enumerate(s, start=1):
    D[c].append(i)

times = 0
cs = 0
for c in t:
    if c not in D.keys():
        print(-1)
        exit()
    else:
        i = bisect.bisect_left(D[c], cs+1)
        if i == len(D[c]):
            times += 1
            cs = D[c][0]
        else:
            cs = D[c][i]
print(times*len(s)+cs)

Solution (Python):
import bisect

s = input()
t = input()

ss = s+s

char = [[] for _ in range(26)]

for i in range(len(ss)):
    char[ord(ss[i])-97].append(i+1)

ans = 0
tmp = 0

for i in range(len(t)):
    if not char[ord(t[i])-97]:
        print(-1)
        break
    
    k = bisect.bisect_right(char[ord(t[i])-97],tmp)
    ans += char[ord(t[i])-97][k]-tmp
    tmp = char[ord(t[i])-97][k]
    if tmp-len(s)>0:
        tmp -= len(s)
    
else:
    print(ans)

Solution (Python):
import sys
sys.setrecursionlimit(2147483647)
INF=float("inf")
MOD=10**9+7
input=lambda:sys.stdin.readline().rstrip()
from collections import defaultdict
from bisect import bisect
def resolve():
    S=input()
    T=input()

    if(len(set(S))!=len(set(S+T))):
        print("-1")
        return

    idx=defaultdict(list)
    for i,s in enumerate(2*S):
        idx[s].append(i)

    now=-1
    n=len(S)
    for t in T:
        i=bisect(idx[t],now%n)
        now+=idx[t][i]-now%n

    print(now+1)
resolve()

Solution (Python):

import bisect

alp = "abcdefghijklmnopqrstuvwxyz"


s = input()
t = input()
ss = s * 2
index = -1
cir = 0
letter = []
res = 0

for i in range(len(ss)):
    letter.append([ss[i], i])


letter.sort()

for i in range(len(t)):
    search = [t[i], index]
    tmp_ind = bisect.bisect(letter, search)
    
    
    
    if tmp_ind == len(ss):
        res = -1
        break
    if t[i] != letter[tmp_ind][0]:
        
        res = -1
        break
    index += (letter[tmp_ind][1] - index)
    if index >= len(s):
        cir += 1
        index -= len(s)
    
    res = cir * len(s) + index + 1

print(res)

Solution (Python):
from bisect import bisect_left
from collections import defaultdict


def solve():
    s = input()
    t = input()

    n = len(s)
    index = defaultdict(list)
    for i, char in enumerate(s):
        index[char] += [i]
    
    cur, orbit = -1, 0
    for char in t:
        target = index[char]
        if not target:
            print(-1)
            exit()
        
        i = bisect_left(target, cur + 1)
        if i < len(target):
            cur = target[i]
        else:
            cur = target[0]
            orbit += 1
    print(n*orbit + cur + 1)


if __name__ == '__main__':
    solve()

Solution (Python):
from collections import Counter,defaultdict,deque
from heapq import heappop,heappush,heapify
import sys,bisect,math,itertools,fractions,pprint
sys.setrecursionlimit(10**8)
mod = 10**9+7
mod2 = 998244353
INF = float('inf')
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sys.stdin.readline().split()))
def inpln(n): return list(int(sys.stdin.readline()) for i in range(n))

s = input()
t = input()


abc = [[] for i in range(26)]
for i,j in enumerate(s):
    tmp = ord(j) - 97
    abc[tmp].append(i)
ln = [0] * 26
for i,j in enumerate(abc):
    ln[i] = len(j)
    
count = 0
p = -1
for i,j in enumerate(t):
    tmp = ord(j) - 97
    if not abc[tmp]:
        print(-1)
        break
    c = bisect.bisect_left(abc[tmp],p+1)
    
    if c == ln[tmp]:
        count += 1
        p = abc[tmp][0]
    else:
        p = abc[tmp][c]
else:
    print(count * len(s) + p + 1)

Solution (Python):
s=input()
t=input()
a=-1
c=0
if not set(t)<=set(s):print(-1);exit()
for i in t:
  a=s.find(i,a+1)
  if a==-1:
    c+=1
    a=s.find(i)
print(c*len(s)+a+1)

Solution (Python):
import sys
import bisect
import collections


def solve():
    readline = sys.stdin.buffer.readline
    mod = 10 ** 9 + 7
    s = str(readline().rstrip().decode('utf-8'))
    d = collections.defaultdict(list)
    for i in range(len(s)):
        d[s[i]] += [i]
    loop = 0
    pos = 0
    t = str(readline().rstrip().decode('utf-8'))
    for i in range(len(t)):
        if t[i] in d:
            pos = bisect.bisect_left(d[t[i]], pos)
            if pos == len(d[t[i]]):
                loop += 1
                pos = 0
                pos = bisect.bisect_left(d[t[i]], pos)
            pos = d[t[i]][pos] + 1
        else:
            print(-1)
            exit()
    print(loop * len(s) + pos)


if __name__ == '__main__':
    solve()

Solution (Python):
import sys
sys.setrecursionlimit(2147483647)
INF=float("inf")
MOD=10**9+7
input=lambda:sys.stdin.readline().rstrip()
from collections import defaultdict
from bisect import bisect_left
def resolve():
    S,T=input(),input()
    if(not (set(S)>=set(T))):
        print(-1)
        return

    D=defaultdict(list)
    for i,s in enumerate(2*S):
        D[s].append(i)

    n=len(S)
    now=0
    ans=0
    for t in T:
        i=bisect_left(D[t],now)
        ans+=D[t][i]-now+1
        now=(D[t][i]+1)%n
    print(ans)
resolve()

Solution (Python):
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10 ** 7)
from collections import defaultdict
from bisect import bisect_left


s = input().rstrip("\n")
len_s = len(s)
t = input().rstrip("\n")
len_t = len(t)

alpha = defaultdict(list)
for i in range(len_s):
    alpha[s[i]].append(i)

if not alpha[t[0]]:
    print(-1)
    exit()
else:
    now_index = alpha[t[0]][0]
    answer = now_index + 1


for i in range(1,len_t):
    index = alpha[t[i]]
    if not index:
        print(-1)
        exit()
    
    next_index = bisect_left(index, now_index+1)
    
    if next_index < len(index):
        answer += index[next_index] - now_index
        now_index = index[next_index]
    else:
        answer += (len_s -1) - now_index + (index[0] + 1)
        now_index = index[0]

print(answer)

Solution (Python):
def main():
  import bisect
  s = input()
  t = input()
  al = [[] for _ in range(26)]
  for i in range(len(s)):
    al[ord(s[i])-97].append(i)
  
  ans = 0
  std = -1
  for i in range(len(t)):
    x = al[ord(t[i])-97]
    if not x:
      print(-1)
      exit()
    y = bisect.bisect_left(x,std+1)
    if y == len(x):
      ans += len(s) - std + x[0]
      std = x[0]
    else:
      ans += al[ord(t[i])-97][y] - std 
      std = al[ord(t[i])-97][y]
  print(ans)
main()

Solution (Python):
import bisect
S = input()
T = input()
OUT = 10**5

N = len(S)
M = len(T)
indice = [0]*M

A = [[] for _ in range(26)]
for i in range(N):
    A[ord(S[i]) - ord('a')].append(i + 1)

res = 0
b = 0
for j in range(M):
    tj = ord(T[j]) - ord('a')
    if len(A[tj]) == 0:
        print(-1)
        exit()
    r = bisect.bisect_right(A[tj], b)
    if len(A[tj]) > r:
        res += A[tj][r] - b
        b = A[tj][r]
    else:
        res += N - b + A[tj][0]
        b = A[tj][0]

print(res)

Solution (Python):
import bisect
s=input()
L=len(s)
s*=2
t=input()
pl={chr(i+97):[] for i in range(26)}
for i in range(len(s)):
  pl[s[i]]+=[i]
cnt=0
rem=0
for i in t:
  if pl[i]==[]:print(-1);exit()
  cnt+=pl[i][bisect.bisect_right(pl[i],rem-1)]-(rem-1)
  rem=cnt%L
print(cnt)

Solution (Python):
import bisect
S = list(input())
T = list(input())
s_dict = {}

for s in S:
    s_dict[s] = []
for i, s in enumerate(S+S):
    bisect.insort_right(s_dict[s], i)

N = len(S)
try:
    ret = 0
    cnt = 0
    pre_t_idx = -1
    for t in T:
        t_idx = s_dict[t][bisect.bisect_right(s_dict[t], pre_t_idx)]
        if t_idx > N-1:
            cnt += 1
            t_idx -= N
        ret = t_idx+1
        pre_t_idx = t_idx

    print(cnt*N+ret)
except Exception as e:
    print(-1)

Solution (Python):

import bisect
import heapq
import math
import random
import sys
import copy
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul, sub

sys.setrecursionlimit(100000)
input = sys.stdin.readline
INF = 2**62-1

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


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


def read_float():
    return float(input())


def read_float_n():
    return list(map(float, input().split()))


def read_str():
    return input().strip()


def read_str_n():
    return list(map(str, input().split()))


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


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap


@mt
def slv(S, T):

    si = defaultdict(deque)
    for i, s in enumerate(S):
        si[s].append(i)

    for k in si:
        si[k].append(-1)

    wsi = si
    used = defaultdict(deque)
    ans = 0
    i = -1
    
    
    for t in T:
        if t not in wsi:
            return -1

        while wsi[t][0] != -1:
            j = wsi[t].popleft()
            used[t].append(j)
            if j > i:
                i = j
                break
        else:
            ans += len(S)
            for k, q in used.items():
                while q:
                    wsi[k].appendleft(q.pop())
            i = wsi[t].popleft()
            used = defaultdict(deque)
            used[t].append(i)
    return ans + i + 1

def f(S, T):
    ans = -1
    ss = S * 1000
    for t in T:
        if t not in S:
            return -1
        for i in range(ans+1, len(ss)):
            if t == ss[i]:
                ans = i
                break
    return ans + 1





def main():
    S = read_str()
    T = read_str()
    print(slv(S, T))

    
    
    
    
    
    


if __name__ == '__main__':
    main()

Solution (Python):
from collections import defaultdict
from bisect import bisect_left

S = input()
T = input()
lenS = len(S)
if set(S) >= set(T):
    SS = S + S
    pos = defaultdict(list)
    for i, s in enumerate(SS): pos[s].append(i)
    ans = -1
    for t in T:
        lb = (ans + 1) % lenS
        nxt = bisect_left(pos[t], lb)
        ans += pos[t][nxt] - lb + 1
    ans += 1
    print(ans)
else:
    print(-1)

Solution (Python):
from collections import defaultdict
from bisect import bisect_left

S = input()
T = input()

SS = S + S
lens = len(S)

index = defaultdict(list) 

for i, ss in enumerate(SS):
    index[ss].append(i)

x = -1 
for t in T:
    arr = index[t]
    if len(arr) == 0:
        x = -2
        break
    y = (x + 1) % lens
    i = bisect_left(arr, y)

    x = (x + 1) + arr[i] - y
    
answer = x + 1
print(answer)

Solution (Python):



import bisect
s = list(input())
t = list(input())
alpha2num = lambda c: ord(c) - ord('a')
count = [0] * 26
count_t = [0] * 26
ind = [[] for _ in range(26)]
for i in range(len(s)):
    count[alpha2num(s[i])] += 1
    ind[alpha2num(s[i])].append(i)
for i in range(len(t)):
    count_t[alpha2num(t[i])] += 1

flag = True
for i in range(26):
    if count_t[i] >= 1 and count[i] == 0:
        flag = False

if flag:
    ans = 0
    tmp = -1
    i = 0
    while True:
        a = bisect.bisect_right(ind[alpha2num(t[i])], tmp)
        
        if 0 <= a < count[alpha2num(t[i])]:
            tmp = ind[alpha2num(t[i])][a]
            i += 1
        else:
            tmp = -1
            ans += 1
        if i >= len(t):
            break
    ans = ans * len(s) + tmp + 1
    print(ans)
else:
    print(-1)

Solution (Python):

from bisect import bisect_right
s = input()
t = input()
p = {c: [] for c in s}
for x, c in enumerate(s):
    p[c].append(x)
z = 0
l = -1
for c in t:
    if c not in p:
        print(-1)
        exit()
    x = bisect_right(p[c], l)
    if x == len(p[c]):
        x = 0
        z += 1
    l = p[c][x]

print(z * len(s) + l + 1)

Solution (Python):

from bisect import bisect_right
s = input()
t = input()
p = {c: [] for c in s}
for x, c in enumerate(s):
    p[c].append(x)
z = 0
l = -1
for c in t:
    if c not in p:
        print(-1)
        break
    x = bisect_right(p[c], l)
    if x == len(p[c]):
        x = 0
        z += 1
    l = p[c][x]
else:
    print(z * len(s) + l + 1)

Solution (Python):
from string import ascii_lowercase
from bisect import bisect_right
s = input()
t = input()
p = {c: [] for c in s}
for x, c in enumerate(s):
    p[c].append(x)
z = 0
l = -1
for c in t:
    if c not in p:
        print(-1)
        break
    x = bisect_right(p[c], l)
    if x == len(p[c]):
        x = 0
        z += 1
    l = p[c][x]
else:
    print(z * len(s) + l + 1)

Solution (Python):
import bisect
import collections
s = input()
t = input()

table = collections.defaultdict(list)
table2 = collections.defaultdict(int)
last = t[-1]
last_id = []
for i, x in enumerate(s):
    table[x].append(i)

for i, x in enumerate(t):
    if x not in table:
        print(-1)
        exit(0)

tmp = 0
id = 0
ans = 0
for x in t:
    l = len(table[x])
    i = bisect.bisect_left(table[x], id)
    if l == i:
        id = 0
        ans += len(s)
        i = bisect.bisect_left(table[x], id)
    id = table[x][i]+1

ans += id


print(ans)

Solution (Python):
S = list(map(lambda x : ord(x)-ord('a'), input().strip()))
T = list(map(lambda x : ord(x)-ord('a'), input().strip()))

L = len(S)

occ = [[] for i in range(26)]
for i, c in enumerate(S):
    occ[c].append(i)

for c in T:
    if occ[c] == []:
        print(-1)
        quit()

total = 0
cur = -1

def getLowest(bound, lo, hi, lst):
    
    while lo < hi:
        mid = lo + (hi - lo) // 2
        if lst[mid] > bound:
            hi = mid
        else:
            lo = mid + 1
    if lst[lo] > bound:
        return lst[lo]
    return lst[0]
        
    

for i, char in enumerate(T):
    newpos = getLowest(cur, 0, len(occ[char])-1, occ[char])
    if cur == newpos:
        total += L
    elif newpos < cur:
        total += L - cur + newpos
    else:
        total += newpos - cur
    cur = newpos
print(total)

Solution (Python):
s = input()
t = input()

dic = {}
for i in range(len(s)):
    if s[i] in dic:
        dic[s[i]].append(i)
    else:
        dic[s[i]] = [i]
        
def f(L, u, l, x):
    if L[-1] <= x:
        return -1
    if u-l < 2:
        if L[l] > x:
            return l
        else:
            return u
    m = (u+l)//2
    if L[m] > x:
        return f(L, m, l, x)
    else:
        return f(L, u, m, x)
    
ans = 0
c = 0 
for i in range(len(t)):
    if t[i] not in dic:
        ans = -1
        break
    idx = f(dic[t[i]], len(dic[t[i]])-1, 0, c-1)

    if idx < 0:
        num = dic[t[i]][0]+1
        ans += len(s)-c+num
        c = num

    else:
        num = dic[t[i]][idx]+1
        ans += num-c
        c = num

        
print(ans)

Solution (Python):
import collections
import bisect

def main():
    s=input()
    t=input()
    s = s*2
    n = len(s)
    cs = collections.Counter(s)
    ct = collections.Counter(t)
    for sct in ct.keys():
        if cs[sct] == 0:
            return -1
    dc = collections.defaultdict(list)
    for i in range(n):
        dc[s[i]].append(i+1)
    res = 0
    ptl = 0
    for i in range(len(t)):
        tl = dc[t[i]][bisect.bisect_left(dc[t[i]],ptl+1)]
        res += tl - ptl
        ptl = tl - n//2 if tl > n//2 else tl
    return res

print(main())

Solution (Python):
import sys
from bisect import bisect_left as bi_l
from collections import defaultdict

def main():
    s, t = sys.stdin.read().split()
    if set(t) - set(s):
        print(-1)
        sys.exit()

    n = len(s)
    s *= 2
    c = defaultdict(list)
    for i in range(n * 2):
        c[s[i]].append(i)

    i = 0
    l = 0 
    for ch in t:
        b = c[ch][bi_l(c[ch], l)]
        if b < n:
            l = b + 1
        else:
            l = b - n + 1
            i += n

    print(i+(l-1)+1) 

if __name__ == '__main__':
    main()

Solution (Python):
from collections import defaultdict
from bisect import bisect_left


def main():
	s = input()
	n = len(s)
	s = s + s
	t = input()
	if set(t) - set(s):
		print(-1)
		exit()
	d = defaultdict(list)
	for i in range(2 * n):
		d[s[i]] += [i]
	cur = ncnt = 0

	for c in t:
		x = d[c][bisect_left(d[c], cur)]
		if x < n:
			cur = x + 1
		else:
			cur = x - n + 1
			ncnt += 1
	print(ncnt*n + cur)


if __name__ == "__main__":
	main()

Solution (Python):
from bisect import bisect
s=input()
t=input()
n,m=len(s),len(t)
alf=list("abcdefghijklmnopqrstuvwxyz")
data=[[] for i in range(26)]
for i in range(26):
    for j in range(n):
        if alf[i]==s[j]:
            data[i].append(j)
l=[0]*26
for i in range(26):
    l[i]=len(data[i])
ind=-1
count=0
for i in range(m):
    k=alf.index(t[i])
    if data[k]:
        p=bisect(data[k],ind)
        if p==l[k]:
            count+=1
            ind=data[k][0]
        else:
            ind=data[k][p]
    else:
        print(-1)
        break
else:
    print(n*count+ind+1)

Solution (Python):

import sys














def main():
    s, t = [s.rstrip() for s in sys.stdin.read().split()]
   
    if set(t) - set(s):
        print(-1)
        sys.exit()

    count = 0
    l = 0
    i = 0
    current = t[i]
    all_found = False
    while not all_found:
        j = s.find(current, l, len(s))
        if j == -1:
            count += len(s)
            l = 0
        else:
            if i == len(t) - 1:
                count += j + 1
                all_found = True
            else:
                if j == len(s) - 1:
                    count += len(s)
                    l = 0
                else:
                    l = j + 1
                i += 1
                current = t[i]
    print(count)



if __name__ == "__main__":
    main()

Solution (Python):

import sys














def main():
    s, t = [s.rstrip() for s in sys.stdin.read().split()]
   
    for l in set(t):
        if not l in s:
            print(-1)
            sys.exit()

    count = 0
    l = 0
    i = 0
    current = t[i]
    all_found = False
    while not all_found:
        j = s.find(current, l, len(s))
        if j == -1:
            count += len(s)
            l = 0
        else:
            if i == len(t) - 1:
                count += j + 1
                all_found = True
            else:
                if j == len(s) - 1:
                    count += len(s)
                    l = 0
                else:
                    l = j + 1
                i += 1
                current = t[i]
    print(count)



if __name__ == "__main__":
    main()

Solution (Python):
from bisect import bisect_left
s, t = [ord(c)-ord('a') for c in input()], [ord(c)-ord('a') for c in input()]
cnt = [[] for i in range(26)]
for i in range(len(s)):
    cnt[s[i]].append(i)
    cnt[s[i]].append(i+len(s))
for i in range(26):
    cnt[i] = sorted(cnt[i])
ans = 0
p = 0
for i in range(len(t)):
    c = t[i]
    if (len(cnt[c]) == 0):
        print('-1')
        exit()
    next = bisect_left(cnt[c], p)
    p = cnt[c][next] + 1
    if (p >= len(s)):
        p -= len(s)
        ans += len(s)
ans += p
print(ans)

Solution (Python):
from collections import defaultdict
import bisect

S = input()
T = input()

d = defaultdict(list)

for i, s in enumerate(S, 1):
    d[s].append(i)

ans = 0
cnt = 0

for t in T:
    c = d[t]
    if len(c)==0:
        print(-1)
        quit()
    if c[-1] <= ans:
        ans = c[0]
        cnt += 1
    else:
        ans = c[bisect.bisect_right(c, ans)]
        
print(len(S)*cnt + ans)

Solution (Python):
s=input()
t=input()
cnt=0
k=0
for i in t:
  f=s.find(i,k)
  if f<0:
    cnt+=1
    f=s.find(i)
    if f==-1:
      print(-1)
      exit()
    else:
      k=f+1
  else:
    k=f+1
print(cnt*len(s)+k)

Solution (Python):
import sys
from bisect import bisect_right

def main():
    s = input()
    t = input()
    
    table = {a : [] for a in 'abcdefghijklmnopqrstuvwxyz'}
    N = len(s)
    
    for idx, a in enumerate(s): table[a].append(idx+1)
    
    length = {a : len(table[a]) for a in 'abcdefghijklmnopqrstuvwxyz'}
    
    loop, idx = 0, 0
    for a in t:
        if not table[a]: 
            print(-1)
            sys.exit()
        
        i = bisect_right(table[a], idx)
        
        if i != length[a]:
            idx = table[a][i]
            if idx == N:
                loop += 1
                idx = 0
        else:
            loop += 1
            idx = table[a][0]
            
    print(loop * len(s) + idx)

if __name__ == '__main__':
    main()

Solution (Python):
import bisect
S=list(input())
T=list(input())
sT=set(T)
N=len(S)
TI={}
for i in range(N):
  s=S[i]
  if s in sT:
    if s in TI:
      TI[s].append(i)
    else:
      TI[s]=[i]

i=-1
for t in T:
  if t not in TI:
    print(-1)
    exit()
  else:
    ni=TI[t][(bisect.bisect_right(TI[t],i%N))%len(TI[t])]
    if ni>i%N:
      i+=ni-i%N
    else:
      i+=N-i%N+ni
print(i+1)

Solution (Python):
import sys
s = input()
t = input()

check = [False]*30
for c in s:
    i = ord(c) - ord("a")
    check[i] = True

for c in t:
    i = ord(c) - ord("a")
    if not check[i]:
        print(-1)
        sys.exit()

dp = [[-1 for i in range(26)] for j in range(len(s))]

s = s + s


def ser(string :str,target :str,s :int):
    for i in range(s,len(string)):
        if string[i] == target:
            return i % (len(string)//2),i-1


def dig(ls,c,v,s,t):
    for i in range(s,t+1):
        ls[i][c] = v

for c in range(len(dp[0])):
    if not check[c]:continue
    i = 0
    while i < len(dp):
        start = i
        v,i = ser(s,chr(c+ord("a")),i+1)
        dig(dp,c,v,start,min(i,len(dp)-1))
        i += 1


import copy
ls = [0 if s[0] == chr(i + ord("a")) else dp[0][i] for i in range(len(dp[0]))]
dp.append(ls)

ans = 0
i = -1
for char in t:
    ikari = dp[i][ord(char) - ord("a")]
    if i >= ikari:
        ans += 1
    i = ikari
print(ans * (len(dp)-1) + 1 + i)

Solution (Python):

import sys
import bisect

def solve(s: str, t: str):
    LENS = len(s)
    dict_s = {} 
    index = [] 

    
    for i in range(LENS):
        if dict_s.get(s[i]) != None:
            dict_s[s[i]].append(i)
        else:
            dict_s[s[i]]= [i]
    
    
    for tt in t:
        if dict_s.get(tt) == None:
            print(-1)
            return
        else:
            index.append(dict_s[tt])
    
    answer = 0
    for i in range(len(index)):
        cur = index[i]

        if i == 0:
            answer += cur[0]
            index[i]=[cur[0]]
            continue

        prev = index[i-1]

        if len(cur)==1:
            if cur[0]>prev[0]:
                answer += cur[0]-prev[0]
            else:
                answer += cur[0]+LENS-prev[0] 
        else: 
            next_index = bisect.bisect_left(cur,prev[0])

            if next_index<len(cur)-1: 
                next_index += 1 if cur[next_index] == prev[0] else 0
                
                answer += cur[next_index]-prev[0]
                index[i]= [cur[next_index]]
            elif next_index==len(cur)-1:
                if prev[0]<cur[next_index]:
                    answer += cur[next_index]-prev[0]
                    index[i] =[cur[next_index]]
                elif prev[0]==cur[next_index]:
                    answer += cur[0]+LENS-prev[0]
                    index[i] =[cur[0]]
            else: 
                answer += cur[0]+LENS-prev[0]
                index[i] = [cur[0]]
       

    print(answer+1)
    return


def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    s = next(tokens)  
    t = next(tokens)  
    solve(s, t)

if __name__ == '__main__':
    main()

Solution (Python):
import bisect
from collections import defaultdict
import sys
sys.setrecursionlimit(10**9)
input = sys.stdin.readline

S = input()[:-1]
T = input()[:-1]


if any(t not in S for t in T):
    print(-1)
    exit()


D = defaultdict(lambda: [])
min_D = defaultdict(lambda: len(S)+1)
for i, s in enumerate(S):
    D[s].append(i)
    min_D[s] = min(i, min_D[s])

for s in D.keys():
    D[s] = sorted(D[s])

cur_pos = 0
repeat = 0
for t in T:
    
    ind = bisect.bisect_left(D[t], cur_pos)
    if ind >= len(D[t]):
        repeat += 1
        cur_pos = min_D[t]+1
    else:
        cur_pos = D[t][ind]+1

print(len(S)*repeat+cur_pos)

Solution (Python):

import bisect,sys

s_ = input()
t = input()

char_s = set(s_)
char_t = set(t)


if not char_s >= char_t:
    print(-1)
    sys.exit()

s = s_+s_

chr_s = {}

l = len(s_)

for i in range(2*l):
    if s[i] in chr_s:
        chr_s[s[i]].append(i)
    else:
        chr_s[s[i]] = [i]

loops = 0
tmp = -1

for i in range(len(t)):
    j = bisect.bisect_right(chr_s[t[i]],tmp)
    tmp = chr_s[t[i]][j]
    
    if tmp>=l:
        loops+=l
        tmp-=l

print(loops+tmp+1)

Solution (Python):
import bisect

s=input()
t=input()

sl=len(s)
tl=len(t)

r="abcdefghijklmnopqrstuvwxyz"
p=[[] for i in range(26)]

for i in range(sl):
  p[r.find(s[i])].append(i)

for i in range(26):
  if len(p[i])>0:
    p[i].append(p[i][0]+sl)

s=set()
for i in range(tl):
  s.add(t[i])
for c in s:
  if len(p[r.find(c)]) == 0:
     print(-1)
     exit()

ti, si = 0, -1
while ti < tl:
  si +=  p[r.find(t[ti])][bisect.bisect_right(p[r.find(t[ti])], si%sl)] - si%sl
  ti += 1

print(si+1)

Solution (Python):
from bisect import*
s=input()
t=input()
if set(t)<=set(s):
    d={}
    for k,j in enumerate(s*2):
        if j in d:
            d[j].append(k)
        else:
            d[j]=[k]
    now=-1
    ans=0
    for i in t:
        nex=d[i][bisect_right(d[i],now)]
        ans+=nex-now
        if nex>=len(s):
            now=nex-len(s)
        else:
            now=nex
    print(ans)

else:
    print(-1)

Solution (Python):
from bisect import*
s=input()
t=input()
if set(t)<=set(s):
    d={}
    for k,j in enumerate(s*2):
        if j in d:
            d[j].append(k)
        else:
            d[j]=[k]
    now=-1
    ans=0
    for i in t:
        nex=d[i][bisect_right(d[i],now)]
        ans+=nex-now
        if nex>=len(s):
            now=nex-len(s)
        else:
            now=nex
    print(ans)

else:
    print(-1)

Solution (Python):
from bisect import*
s=input()
t=input()
if set(t)<=set(s):
    d={}
    for k,j in enumerate(s*2):
        if j in d:
            d[j].append(k)
        else:
            d[j]=[k]
    
    now=-1
    ans=0
    for _,i in enumerate(t):
        nex=d[i][bisect_right(d[i],now)]
        ans+=nex-now

        
        
        if nex>=len(s):
            now=nex-len(s)
        else:
            now=nex
    print(ans)

else:
    print(-1)