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):
from collections import deque
import bisect
s = input()
t = input()
N = len(s)
dict = {}
for i in range(N):
  if s[i] in dict.keys():
    dict[s[i]].append(i)
  else:
    dict[s[i]] = [i]
cur = -1
count = 1
for i in range(len(t)):
  if t[i] not in dict.keys():
    print(-1)
    exit()
  if cur <= dict[t[i]][-1]:
    tmp = bisect.bisect_left(dict[t[i]],cur)
    cur = dict[t[i]][tmp] + 1
  else:
    count += 1
    cur = dict[t[i]][0] + 1

ans = (count-1)*N + cur
print(ans if count <= 10**100 else -1)

Solution (Python):
from collections import defaultdict
import bisect

s = input()
t = input()
s_set = set(list(s))
t_set = set(list(t))




if t_set <= s_set:
    str_dict = defaultdict(list)
    for i, cha in enumerate(s):
        str_dict[cha].append(i)
    

    times = 0
    now = 0

    for i, c in enumerate(t):
        target_char = str_dict[c]
        if target_char[-1] < now:  
            times += 1
            now = target_char[0]+1
        else:
            now = target_char[bisect.bisect_left(target_char, now)]+1
        
    print(len(s) * times + now)

else:
    print(-1)

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

table = {}
for ti in t:
    table[ti] = []
    
for i, si in enumerate(s):
    
    if table.get(si) != None:
        table[si].append(i)



import bisect

if [] in table.values():
    print(-1)
else:
    ans = 0
    pos = min(table[t[0]])
    for i in range(len(t) - 1):
        src = t[i]
        dst = t[i + 1]
        idx_tmp = bisect.bisect_right(table[dst], pos)
        if idx_tmp == len(table[dst]):
            ans += len(s)
            pos = table[dst][0]
        else:
            pos = table[dst][idx_tmp]
        
    
    print(ans + pos + 1)

Solution (Python):

from bisect import bisect_right as br

def main():
    S = [s for s in input()]
    T = [t for t in input()]
    slen = len(S)
    tlen = len(T)

    dic = {}
    for i in range(slen):
        if S[i] in dic:
            dic[S[i]].append(i)
        else:
            dic[S[i]] = [i]

    ans = 0
    pre = 0
    if T[0] in dic:
        if T[0] != S[0]:
            ans = dic[T[0]][0]
            pre = dic[T[0]][0]
    else:
        print(-1)
        return 

    for j in range(1,tlen):
        t = T[j]
        if t in dic:
            point = br(dic[t],pre)
            if point == len(dic[t]):
                ans += slen - pre + dic[t][0]
                pre = dic[t][0]
            else:
                if pre == dic[t] == point:
                    ans += slen
                else:
                    ans += dic[t][point] - pre
                    pre = dic[t][point]
        else:
            print(-1)
            return
    print(ans + 1)
    return 
main()

Solution (Python):
import bisect
from collections import defaultdict
S = input()
T = input()
len_S = len(S)
s2i = defaultdict(list)
for i, si in enumerate(S):
    s2i[si].append(i)
ans = 1
pi = -1
for ti in T:
    si = s2i.get(ti)
    if not si:
        ans = -1
        break
    il = bisect.bisect_right(si,pi)
    if len(si) <= il:
        ans += len_S
        pi = si[0]
    else:
        pi = si[il]

if ans != -1:
    ans += pi

print(ans)

Solution (Python):
import bisect
s = list(input())
t = input()
size = len(s)


dic = {}
for c in t:
	if c in dic:
		continue
	dic[c] = [i for i,val in enumerate(s) if val==c]
	if len(dic[c]) == 0:
		print(-1)
		exit()

pos =-1 
loop = 0
for c in t:
	l = dic[c]
	
	if pos < l[-1]:
		index = bisect.bisect_right(l,pos)
		pos = l[index]
	else:
		pos = l[0]
		loop += 1
	

print(loop*size + pos+1)

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

S = list(s)

C = [[]for i in range(26)]
for i in range(len(S)):
    C[ord(S[i])-97].append(i+1)

idx = 0
ans = 0
l = len(s)
for i in range(len(t)):
    now = ord(t[i])-97
    if C[now] == []:
        ans = -1
        break
    up = bisect.bisect_right(C[now], idx)
    if up >= len(C[now]):
        up = bisect.bisect_right(C[now], 0)
        ans += C[now][up] + l-idx
        idx = C[now][up]
    else:
        ans += C[now][up] - idx
        idx = C[now][up]

print(ans)

Solution (Python):
s = input()
t = input()
s_set = set(list(s))
t_set = set(list(t))
if not t_set.issubset(s_set):
    print(-1)
else:
    ans = 0
    pre_idx = -1
    cnt = 0
    for i in range(len(t)):
        if t[i] not in s[pre_idx+1:]:
            ans += len(s)
            pre_idx = -1
            cnt = 0
        if pre_idx == -1:
            idx = s[pre_idx+1:].find(t[i])
        else:
            idx = s[pre_idx+1:].find(t[i]) + pre_idx + 1
        cnt = idx+1
        pre_idx = idx
    print(ans+cnt)

Solution (Python):
import sys
stdin = sys.stdin
sys.setrecursionlimit(10**6)
 
ni = lambda: int(ns())
na = lambda: list(map(int, stdin.readline().split()))
nn = lambda: list(stdin.readline().split())
ns = lambda: stdin.readline().rstrip()

s = ns()
t = ns()
n = len(s)
g = {}

for i in range(n):
    if s[i] not in g:
        g[s[i]] = [i]
    else:
        g[s[i]].append(i)

import bisect

a = 0
b = -1
for i in t:
    if i not in g or a >= n*(10**100):
        print(-1)
        exit()
    k = bisect.bisect_left(g[i],b)
    if k == len(g[i]):
        b = g[i][0]+1
        a += 1
    else:
        b = g[i][k]+1

print(n*a+b)

Solution (Python):


import sys
from collections import defaultdict
from bisect import bisect_right

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 ceil(x, y=1): return int(-(-x // y))
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
MOD = 10 ** 9 + 7

S = input()
T = input()
N = len(S)

d = defaultdict(list)
for i, s in enumerate(S):
    d[s].append(i)
for k, v in d.items():
    d[k].append(INF)

cur = -1
ans = 0
for i, t in enumerate(T):
    if t not in d:
        print(-1)
        exit()
    idx = bisect_right(d[t], cur)
    if d[t][idx] == INF:
        ans += N
        cur = d[t][0]
    else:
        cur = d[t][idx]
ans += cur+1
print(ans)

Solution (Python):
import copy
s = input()
t = input()
if(set(t) - set(s)):
  print(-1)
  exit()

t_index = 0
s_index = 0
count = 0
copy_s = copy.deepcopy(s)
while len(t) > t_index:
  index = copy_s.find(t[t_index])
  if index >= 0:
    t_index+=1
    copy_s = copy_s[index+1:]
  else:
    copy_s = copy.deepcopy(s)    
    count += 1
print(count*len(s)+len(s)-len(copy_s))

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

def sol():
    S = input()
    T = input()

    setS = set(S)
    setT = set(T)
    for t in setT:
        if not t in setS:
            print('-1')
            return

    posS = defaultdict(list)

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

    for s in enumerate(S):
        posS[s].sort()

    prev = -1
    ans = 0
    N = len(S)

    for t in T:
        next = bisect_right(posS[t], prev)
        if next >= len(posS[t]):
            ans += N - prev
            ans += posS[t][0]
            prev = posS[t][0]
        else:
            ans += posS[t][next] - prev
            prev = posS[t][next]

    print(ans)

sol()

Solution (Python):
import bisect

def main():
    S = input()
    dS = {c : [] for c in 'abcdefghijklmnopqrstuvwxyz'}

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

    

    T = input()
    ans = 0

    p = 0

    for t in T:
        if not dS[t]:
            print(-1)
            return
        if dS[t][-1] < p:
            p = 0
            ans += len(S)
        idx = bisect.bisect_left(dS[t], p)
        p = dS[t][idx] + 1
    
    print(ans + p)

main()

Solution (Python):
import bisect
s=input()
t=input()
s_set=set([i for i in s])
t_set=set([i for i in t])
if t_set-s_set&t_set:
  print(-1)
  exit()
a={}
for i in t_set:
  a[i]=[]
  for k,j in enumerate(s):
    if j==i:
      a[i].append(k)
  a[i].sort()
ans=0
j=0
for i in t:
  if a[i][-1]<j:
    ans+=len(s)
    j=0
  k=bisect.bisect_left(a[i],j)
  j=a[i][k]+1
print(ans+j)

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

sc = [0] * 26
tc = [0] * 26

for i in range(len(s)):
    sc[ord(s[i]) - ord("a")] += 1
for i in range(len(t)):
    tc[ord(t[i]) - ord("a")] += 1


for i in range(26):
    if tc[i] > 0 and sc[i] == 0:
        print(-1)
        exit()


alph = [[] for _ in range(26)]
for i in range(len(s)):
    alph[ord(s[i]) - ord("a")].append(i)

ans = [0] * len(t)
pre_num = -1
for i in range(len(t)):
    num = ord(t[i]) - ord("a")
    if i > 0:
        idx = bisect.bisect_right(alph[num], pre_num)
        if idx >= len(alph[num]):
            num_idx = alph[num][0]
        else:
            num_idx = alph[num][idx]
    else:
        num_idx = alph[num][0]
    ans[i] = num_idx
    pre_num = num_idx

count = 0
pre = -1
for v in ans:
    if pre >= v:
        count += 1
    pre = v

print(count * len(s) + ans[-1] + 1)

Solution (Python):


from bisect import bisect_left


def solve(s, t):
    a = ord('a')
    pos_list = [[] for _ in range(26)]
    for i, ch in enumerate(s):
        pos_list[ord(ch)-a].append(i)
    for ch in t:
        if not pos_list[ord(ch)-a]:
            return -1
    cc = 0
    s_len = len(s)
    for ch in t:
        pl = pos_list[ord(ch)-a]
        cc_mod = cc % s_len
        cc_ofs = (cc // s_len) * s_len
        i = bisect_left(pl, cc_mod)
        if i < len(pl):
            cc = cc_ofs + pl[i] + 1
        else:
            cc = cc_ofs + s_len + pl[0] + 1

    return cc


if __name__ == '__main__':
    s = input().strip()
    t = input().strip()

    ans = solve(s, t)

    print(ans)

Solution (Python):


import sys
from collections import defaultdict
from bisect import bisect_right

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 ceil(x, y=1): return int(-(-x // y))
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
MOD = 10 ** 9 + 7

S = input()
T = input()
N = len(S)

d = defaultdict(list)
for i, s in enumerate(S):
    d[s].append(i)
for k, v in d.items():
    d[k].append(INF)

cur = -1
ans = 0
for i, t in enumerate(T):
    if t not in d:
        print(-1)
        exit()
    idx = bisect_right(d[t], cur)
    if d[t][idx] == INF:
        ans += N
        cur = d[t][0]
    else:
        cur = d[t][idx]
ans += cur+1
print(ans)

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

s_dict = {}
from bisect import insort_right, bisect_right
for i, c in enumerate(s):
    if c in s_dict:
        insort_right(s_dict[c], i)
    else:
        s_dict[c] = [i]


def find_gt(a, x):
    'Find leftmost value greater than x'
    i = bisect_right(a, x)
    if i != len(a):
        return a[i]
    raise ValueError

idx = -1
cnt = 1
bad = False
for c in t:
    if not c in s_dict:
        bad = True
        break
    try:
        idx = find_gt(s_dict[c], idx)
    except:
        idx = -1
        idx = find_gt(s_dict[c], idx)
        cnt += 1



if bad:
    print(-1)
else:
    ans = len(s) * (cnt-1) + (idx+1)
    print(ans)

Solution (Python):
import bisect
S=input()
T=input()

A=set(S)
B=set(T)

if B-A:print(-1)
else:
    d={}
    for b in B:
        d[b]=[i for i in range(len(S)) if S[i]==b]
    c=-1
    p=0
    for t in T:
        idx=bisect.bisect_right(d[t],c)
        if idx == len(d[t]):
            c=d[t][0]
            p+=1
        else:
            c=d[t][idx]
    print(len(S)*p+c+1)

Solution (Python):
import sys

s1 = input()
s2 = input()

n1 = 0
t1 = 0
t2 = -1

for i1 in range(len(s2) ):
    t1 =  s1.find(s2[i1],t2 + 1)
    if t1 == -1:
        t1 = s1.find(s2[i1], 0, t2 + 1)
        if t1 == -1:
            print(t1)
            sys.exit()
        else:
            n1 += t1 + (len(s1) - t2)
    else:
        n1 += t1 - t2
    t2 = t1

print(n1)

Solution (Python):
import bisect
from collections import defaultdict

S = input()
T = input()

if set(T) - set(S) != set():
    print(-1)
    exit()

d = defaultdict(list)
l = [0 for _ in range(26)]

for i, v in enumerate(S, 1):
    l[ord(v)-ord('a')] += 1
    d[v].append(i)

len_S = len(S)



ans = 0
c = 0
for t in T:
    i = bisect.bisect_left(d[t], c)
    
    if i < l[ord(t)-ord('a')]:
        ans += d[t][i]-c+1
        c = d[t][i]+1
        
    else:
        
        ans += len_S-c+d[t][0]+1
        c = d[t][0]+1
    

if ans > 10**100*len_S:
    print(-1)
else:
    print(ans-1)

Solution (Python):
from bisect import *
s=input()
t=input()
a=[[]for i in range(26)]
for i in range(len(s)):
    a[ord(s[i])-97].append(i+1)
p=-1
b=[len(i)for i in a]
r=0
for i in t:
    if b[ord(i)-97]==0:
        print(-1)
        break
    c=bisect_right(a[ord(i)-97],p)
    if c==b[ord(i)-97]:
        r+=1
        p=a[ord(i)-97][0]
    else:
        p=a[ord(i)-97][c]
else:
    print(r*len(s)+p)

Solution (Python):
import sys
stdin = sys.stdin

sys.setrecursionlimit(10 ** 7)

def li(): return map(int, stdin.readline().split())
def li_(): return map(lambda x: int(x) - 1, stdin.readline().split())
def lf(): return map(float, stdin.readline().split())
def ls(): return stdin.readline().split()
def ns(): return stdin.readline().rstrip()
def lc(): return list(ns())
def ni(): return int(stdin.readline())
def nf(): return float(stdin.readline())

from collections import defaultdict
from bisect import bisect_right

s = ns()
t = ns()

ok = True

sset = set(list(s))
for ti in t:
    if ti not in sset:
        ok = False
        break

if not ok:
    print(-1)

else:
    n = len(s)

    charidx = defaultdict(list)

    for i, si in enumerate(s):
        charidx[si].append(i)
    for i, si in enumerate(s):
        charidx[si].append(n+i)

    ks = charidx.keys()

    move = [{ki: -1 for ki in ks} for _ in range(n)]

    for i, si in enumerate(s):
        for ki in ks:
            idxlist = charidx[ki]
            nexidx = bisect_right(idxlist, i)
            move[i][ki] = (idxlist[nexidx] - i) % (n+1)

    cur = s.index(t[:1])
    ans = cur
    for ti in t[1:]:
        nex = move[cur][ti]
        ans += nex
        cur = (cur + nex) % n

    print(ans+1)

Solution (Python):
s = input()
t = input()
count = 0
stock = 0
check = 0

for i in t:
    if check==0:
        if i in s:
            stock = s.index(i)
            check = 1
        else:
            count = -1
            break
    else:
        if i in s:
            if stock==len(s)-1:
                count += 1
                stock = s.index(i)
                continue
            if i in s[stock+1:]:
                stock = s[stock+1:].index(i) + stock + 1
                continue
            else:
                count += 1
                stock = s.index(i)
                continue
        else:
            count = -1
            break
        
if count==-1:
    print(count)
else:
    print(count*len(s)+stock+1)

Solution (Python):
import bisect
s = input().rstrip()
t = input().rstrip()

a_ord = ord("a")
ch_place = [[] for _ in range(26)]
for i, ch in enumerate(s):
    ch_place[ord(ch) - a_ord].append(i)



count = 0
idx = -1 
for ch in t:
    ch_num = ord(ch) - a_ord
    if len(ch_place[ch_num]) == 0:
        print(-1)
        exit()
    place = bisect.bisect_right(ch_place[ch_num], idx)
    
    if place == len(ch_place[ch_num]):
        idx = ch_place[ch_num][0]
        count += 1
    else:
        idx = ch_place[ch_num][place]


print(count * len(s) + idx + 1)

Solution (Python):


import bisect

def f(D, T, lenOfS):
    x = 0
    p = -1
    for c in T:
        d = D[ord(c) - 97]
        if len(d) == 0:
            return -1
            
        idx = bisect.bisect_left(d, p+1)

        if idx < len(d):
            p2 = d[idx]
        else:
            p2 = d[0]
            x += lenOfS;

        x += (p2 - p)
        p = p2
            
    return x


def main():
    S = input()
    T = input()

    D = [[] for _ in range(26)]
    for i, c in enumerate(S):
        D[ord(c) - 97].append(i)

    print(f(D, T, len(S)))
    

if __name__ == '__main__':
    main()

Solution (Python):
import sys
def input(): return sys.stdin.readline().strip()

S  = lambda: input()

s = S()
t = S()

count = 0
loop = -1
s_index = 0
t_index = 0
is_ok = True
while True:
  loop += 1
  s_index = 0
  if t[t_index] not in s:
    is_ok = False
    break

  while t[t_index] in s[s_index:]:
    s_index += s[s_index:].find(t[t_index]) + 1
    t_index += 1
    if t_index == len(t):
      break
  
  if t_index == len(t):
      break

if is_ok:
  print(loop * len(s) + s_index)
else:
  print(-1)

Solution (Python):
import sys
from collections import defaultdict
import bisect
sys.setrecursionlimit(10**7)
INF = 10 ** 18
MOD = 10 ** 9 + 7
def LI(): return list(map(int, sys.stdin.readline().split()))
def II(): return int(sys.stdin.readline())
def LS(): return list(map(list, sys.stdin.readline().split()))
def S(): return sys.stdin.readline()[:-1]

def main():
    s = list(S())
    t = list(S())

    alfa = defaultdict(list)
    for i, c in enumerate(s):
        alfa[c].append(i)
    pre = -1
    ans = 0
    for i, c in enumerate(t):
        index = alfa[c]
        if len(index) == 0:
            print(-1)
            return
        a = bisect.bisect_right(index, pre)
        if a != len(index):
            pre = index[a]
        else:
            pre = index[0]
            ans += len(s)

    print(ans + pre + 1)
if __name__ == '__main__':
    main()

Solution (Python):
from bisect import bisect_right,bisect_left
alphabet_small = [chr(i) for i in range(97, 97+26)]
s = input()
t = input()
m = len(s)
n = len(t)

alpha = [[] for i in range(26)]
for i,let in enumerate(s):
    for j,al in enumerate(alphabet_small):
        if let == al:
            alpha[j].append(i)



dp = [0 for i in range(n+1)] 

t_num = []
append = t_num.append
for let in t:
    for j,al in enumerate(alphabet_small):
        if let == al:
            t_num.append(j)


now = -1
for i,let_num in enumerate(t_num):
    
    if len(alpha[let_num]) == 0:
        print(-1)
        exit()
    else:
        q = bisect_right(alpha[let_num], now)
        
        if q != len(alpha[let_num]):
            next = alpha[let_num][q]
            
            if now == next:
                dp[i+1] += m
                
            dp[i+1] += dp[i] + next - now
        else:
            next = alpha[let_num][0]
            dp[i+1] += dp[i] + next - now + m
        now = next



print(dp[n])

Solution (Python):
from bisect import bisect_left
s = input()
t = input()
pos = {}
for i, c in enumerate(s):
    if c not in pos:
        pos[c] = [i]
    else:
        pos[c].append(i)
ans = 0
pre = -1
for c in t:
    if c not in pos:
        print(-1)
        exit()
    l = bisect_left(pos[c], pre+1)
    if l >= len(pos[c]):
        p = pos[c][0]
        ans += len(s)
    else:
        p = pos[c][l]
    ans += p - pre
    
    pre = p

print(ans)

Solution (Python):
import bisect
s=list(input())
t=list(input())
N=len(s)
sd={x:[] for x in sorted(set(s))}
if not set(t) <= set(sd.keys()):
    print(-1)
    exit()

for i,c in enumerate(s):
    sd[c].append(i)
index=-1
ans=0
for c in t:
    i=bisect.bisect_left(sd[c],index+1)

    if i==len(sd[c]):
        ans+=1
        i=bisect.bisect_left(sd[c],0)
    index=sd[c][i]
print(ans*N+index+1)

Solution (Python):
import sys
input=sys.stdin.readline
s=input().rstrip()
t=input().rstrip()
m=len(s)
D=[[] for i in range(26)]
for i in range(m):
    D[ord(s[i])-97].append(i)
import sys
import bisect
now=-1
ans=0
for i in t:
    if D[ord(i)-97]==[]:
        print(-1)
        sys.exit()
    p=bisect.bisect(D[ord(i)-97],now)
    if p==len(D[ord(i)-97]):
        ans+=m-1-now
        now=D[ord(i)-97][0]
        ans+=now+1
    else:
        ans+=D[ord(i)-97][p]-now
        now=D[ord(i)-97][p]
print(ans)

Solution (Python):
import bisect

s = list(input())
t = list(input())
len_s = len(s)
LEN = [0] * 26
s_set = set(s)
t_set = set(t)
d = [None] * 26
ans = 0
now = -1
if s_set >= t_set:
  for key,i in enumerate(s):
    index = ord(i) - ord("a")
    if d[index] == None:
      d[index] = [key]
    else:
      d[index].append(key)
    LEN[index] += 1
  for j in t:
    ORD = ord(j) - ord("a")
    g = bisect.bisect_right(d[ORD],now)
    if g == LEN[ORD]:
      ans += len_s
      now = d[ORD][0]
    else:
      now = d[ORD][g]
  ans += now + 1
  print(ans)
else:
  print(-1)

Solution (Python):
S=list(input())

A=["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
L=[[]for i in range(26)]
for i in range(len(S)):
    for j in range(26):
        if S[i]==A[j]:
            L[j].append(i+1)

T=list(input())
M=[[]for i in range(26)]
for i in range(len(T)):
    for j in range(26):
        if T[i]==A[j]:
            M[j].append(i+1)
            T[i]=j



for i in range(26):
    if M[i] !=[] and L[i]==[]:
        print(-1)
        exit()

import math
import bisect
ans=0
mo=0
for i in T:
    if L[i][-1]<=ans:
        mo+=ans//len(S)
        ans%=len(S)
        if L[i][-1]<=ans:
            mo+=1
            ans-=len(S)
    ans=L[i][bisect.bisect_right(L[i],ans)]
    
print(mo*len(S)+ans)

Solution (Python):
s = input()
t = input()
ls,lt = len(s),len(t)
i = j = 0
si = lp = 0
while True:
    tc = t[i]
    si = s.find(tc)
    if si == -1:
        print(-1)
        exit(0)
    else:
        if i == lt-1:
            print(lp*ls + si+1)
            exit(0)
        else:
            while True:
                if t[i+1] in s[si+1:]:
                    si = s[si+1:].find(t[i+1]) + si +1
                    if i+1 == lt-1:
                        print(lp*ls + si+1)
                        exit(0)
                    else:
                        i+=1
                else:
                    i+=1
                    break
    lp += 1
    if i >= lt:
        print(-1)
        break

Solution (Python):
from bisect import bisect_left, bisect_right


def main():
    S = list(input())
    T = list(input())
    sl = len(S)

    Sdic = {}
    for i, s in enumerate(S):
        if not s in Sdic.keys():
            Sdic[s] = [i]
        else:
            Sdic[s].append(i)
    pret = -1
    ans = 0
    for t in T:
        try:
            
            it = bisect_right(Sdic[t], pret)
            
            if it < len(Sdic[t]):
                pret = Sdic[t][it]
            else:
                ans += sl
                pret = Sdic[t][0]
            
        except KeyError:
            ans = -1
            break
    if ans != -1:
        ans += pret+1
    print(ans)

if __name__ == "__main__":
    main()

Solution (Python):
import bisect

s = input()
t = input()

idx = {}
l = len(s)

for i in range(l):
  ch = s[i]
  if ch in idx:
    arr = idx[ch]
    _idx = bisect.bisect_right(arr, i + 1)
    arr.insert(_idx, i + 1)
    idx[ch] = arr
  else:
    idx[ch] = [i + 1]

ans = 0

for ch in t:
  if ch in idx:
    arr = idx[ch]
    __idx = bisect.bisect_right(arr, ans % l)
    if __idx == len(arr):
      ans = -(-ans // l) * l + arr[0]
      _idx = arr[0]
    else:
      ans = (ans // l) * l + arr[__idx]
      _idx = arr[__idx]
  else:
    ans = -1
    break

print(ans)

Solution (Python):

import sys
from collections import deque, defaultdict
import copy
import bisect


import math
import heapq

s = input()
t = input()

word = defaultdict(int)
for i in range(len(s)):
	if type(word[s[i]]) == int:
		word[s[i]] = []
	bisect.insort(word[s[i]], i)

loc = 0
ret = 0
for i in range(len(t)):
	if word[t[i]] == 0:
		print(-1)
		exit()
	else:
		select = bisect.bisect_left(word[t[i]], loc)
		if select == len(word[t[i]]):
			ret += 1
			loc = word[t[i]][0] + 1
		else:
			loc = word[t[i]][select] + 1
print(ret*len(s) + loc)

Solution (Python):
def solve(s, t):
    ls = len(s)
    nxt = {}
    follow = [{} for _ in range(ls + 1)]
    for i, c in enumerate(s[::-1]):
        i = ls - i
        follow[i] = nxt.copy()
        nxt[c] = i
    follow[0] = nxt.copy()
    ans = 0
    i = 0
    for c in t:
        if c not in follow[i]:
            if c not in follow[0]:
                return -1
            ans += len(s)
            i = follow[0][c]
            continue
        i = follow[i][c]
    return ans + i


s = input()
t = input()
print(solve(s, t))

Solution (Python):
import string
import bisect

s=input()
t=input()
tng=len(t)
sng=len(s)

komoji=string.ascii_lowercase
kjlist=[]
kjlist2=[]
mada=[]
for kj in komoji:
    kjlist.append([kj, []])
    kjlist2.append(kj)
    mada.append(kj)

for tt in range(sng):
    ban=kjlist2.index(s[tt])
    kjlist[ban][1].append(tt)

kosu=0
now=-1
nasi=0
zerosw=0
for ss in range(tng):
    ban=kjlist2.index(t[ss])
    if len(kjlist[ban][1])>0:
        basho=bisect.bisect_right(kjlist[ban][1], now)
        if basho==len(kjlist[ban][1]):
            now=kjlist[ban][1][0]
            maekos=kosu
            kosu=(int(kosu/sng)+1)*sng+now
        else:
            now=kjlist[ban][1][basho]
            maekos=kosu
            kosu=int(kosu/sng)*sng+now
    else:
        nasi=1
    
if nasi==0:
    print(kosu+1)
else:
    print(-1)

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

l = len(s)
dic = {c: [0] * l for c in set(s)}

for i in range(l):
    dic[s[i]][i] = 1

for key in dic.keys():
    lst = dic[key]
    for i in range(l - 1):
        lst[i + 1] += lst[i]

idx = -1
ans = 0
for c in t:
    if not c in dic:
        print(-1)
        exit(0)
    lst = dic[c]
    cur = lst[idx] if idx >= 0 else 0
    i = bisect_left(lst, cur + 1)
    if i == l:
        ans += l
        idx = -1
        cur = 0
        i = bisect_left(lst, 1)

    idx = i
ans += idx
print(ans + 1)

Solution (Python):
s = input()
t = input()
pre_index = 0
ans = 0
for i in t:
  if i not in s:
    ans = -1
    break
  else:
    temp = s[pre_index:]
    if i in temp:
      ans += (temp.index(i)+1)
      pre_index+= (temp.index(i)+1)
    else:
      ans += len(temp)
      pre_index = (s.index(i)+1)
      ans += pre_index
print(ans)

Solution (Python):
from bisect import bisect

from string import ascii_lowercase

s = input()
t = input()

dp = {c: [] for c in ascii_lowercase}
for i, c in enumerate(s):
    dp[c].append(i)

N = len(s)
ans = 0
prev = -1

for c in t:
    if not dp[c]:
        ans = -1
        break
    i = bisect(dp[c], prev)
    if i == len(dp[c]):
        i = 0
    k = dp[c][i]
    
    if k > prev:
        d = k - prev
    elif k == prev:
        d = N
    else:
        d = N + k - prev
    
    ans += d
    prev = dp[c][i]
print(ans)

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

d=dict()
for i in "abcdefghijklmnopqrstuvwxyz":
    d[i]=[]
for i,c in enumerate(s):
    d[c].append(i)

now=0
ans=0
for c in t:
    l=len(d[c])
    if l==0:
        print(-1)
        break
    i=bisect.bisect_left(d[c],now)
    if i<l:
        now=d[c][i]+1
    else:
        ans+=len(s)
        i=bisect.bisect_left(d[c],0)
        now=d[c][i]+1
else:
    ans+=now
    print(ans)

Solution (Python):
s = input()
t = input()
sn = len(s)
tn = len(t)

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

for i in range(sn):
    number = ord(s[i]) - ord('a')
    alpha[number].append(i)

dist = [[-1 for i in range(26)] for j in range(sn)]
    
for i in range(26):
    if(len(alpha[i]) >= 1):
        now=0
        prev=0
        for j in range(len(alpha[i])):
            val = alpha[i][j]
            for k in range(val-prev):
                dist[now][i] = val-now
                now += 1
            prev=now
        val = alpha[i][0]
        for k in range(sn-prev):
            dist[now][i] = val-now+sn
            now += 1
            



prev = sn-1
ans = 0
for i in range(tn):
    d = dist[prev][ord(t[i]) - ord('a')]
    if(d==-1):
        ans = -1
        break
    ans += d
    prev = (prev + d)%sn
    
print(ans)

Solution (Python):
s = input()
t = input()
r = 0
p = 0
x = 0
for i in t:
    if s.find(i) == -1:
        print(-1)
        exit()
    if p > s.find(i):
        if s[p:].find(i) == -1:
            x += 1
            p = s.find(i) + 1
        else:
            p = p + s[p:].find(i) + 1
    else:
        p = s.find(i) + 1
print(x * len(s) + p)

Solution (Python):

import bisect

s = input()
t = input()

dic = {}

for i in range(len(s)):

    if s[i] not in dic:

        dic[s[i]] = [i]

    else:

        dic[s[i]].append(i)

roop = 0
point = -1
flag = True

for i in range(len(t)):


    if t[i] not in dic:
        flag = False
        break

    ind = bisect.bisect_left(dic[t[i]],point)

    if ind >= len(dic[t[i]]):
        roop += 1
        point = dic[t[i]][0] + 0.1

    else:
        point = dic[t[i]][ind] + 0.1


if flag:
    print (len(s) * roop + int(point) + 1)

else:
    print (-1)

Solution (Python):
s=input()
t=input()
x=list(s)
y=list(t)
import sys
if len(set(y)-set(x))!=0:
	print(-1)
	sys.exit()
a=[[] for _ in range(26)]
for i in range(len(s)):
	a[ord(x[i])-97].append(i)
import bisect

repeat=0
last=-1
for i in range(len(t)):
	temp=a[ord(y[i])-97]
	if last>=temp[-1]:
		repeat+=1
		last=temp[0]
	else:
		last=temp[bisect.bisect_right(temp,last)]
	
print(repeat*len(s)+last+1)

Solution (Python):
s = input()
t = input()
temp = -1
cycle = 0
ans = True
for tt in t:
    if tt in s[temp+1:]:
        k = s[temp+1:].find(tt)
        temp += k + 1
    elif tt in s:
        temp = s.find(tt)
        cycle += 1
    else:
        ans = False
        break
if ans:    
    print((cycle*len(s)) + temp + 1)
else:
    print(-1)

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


s_set = set(s)
s_len = len(s)

if all((t_ in s_set) for t_ in t):
    ans = 0
    ss = s + s
    found_index_old = -1

    for t_ in t:
        found_index = ss.find(t_, found_index_old + 1)
        
        ans += found_index - found_index_old 
        found_index_old = found_index % s_len
    print(ans)
else:
    print(-1)