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 bisect
s=input()
t=input()
jisho={}
alphabets = [chr(ord('a') + i) for i in range(26)]
for moji in alphabets:
    jisho[moji] = [i for i,x in enumerate(s) if x==moji]
lis = [jisho[moji] for moji in t]

if [] in lis:
    print(-1)
else:    
    old=-1
    count=0
    for cand in lis:
        z=bisect.bisect(cand,old)
        if z==len(cand):
            num=min(cand)
        else:
            num=cand[z]





        if num<=old: count+=1
        old=num
    print(count*len(s)+old+1)

Solution (Python):
s=input()
t=input()
import bisect
res=0
if len(set(t)-set(s)) > 0:
    res=-1
else:
    pos={}
    set_t=set(t)
    for e_t in t:
        pos[e_t]=[]
    for i in range(len(s)):
        if s[i] in set_t:
            pos[s[i]].append(i+1)
    cur = 0
    nxt=0
    for e_t in t:
        nxt=bisect.bisect_left(pos[e_t], cur+1)
        if nxt < len(pos[e_t]):
            cur=pos[e_t][nxt]
        else:
            cur=pos[e_t][0]
            res+=len(s)
    res+=cur
print(res)

Solution (Python):
from bisect import bisect
import sys
s = input()
t = input()
l = {}
for c in set(t):
    cl = [s.find(c)]
    if cl[0] == -1:
        print("-1")
        sys.exit()
    while True:
        i = s.find(c, cl[-1] + 1)
        if (i == -1):
            break
        cl.append(i)
    l[c] = cl
ofs = -1
count = 0
for c in t:
    lens = len(s)
    ref = bisect(l[c], ofs)
    if ref < len(l[c]):
        ofs = l[c][ref]
    else:
        ofs = l[c][0]
        count += 1
print(lens * count + ofs + 1)

Solution (Python):

from bisect import bisect_left as bs
from collections import defaultdict


def main():
    S, T = tuple(input() for _ in range(2))
    idx, ls = defaultdict(list), len(S)
    for i, s in enumerate(S):
        idx[s] += [i]
    roop, cur = 0, -1
    for t in T:
        tgt = idx[t]
        if tgt == []:  
            print(-1)
            return
        x = bs(tgt, cur + 1)
        if x < len(tgt):
            cur = tgt[x]
        else:
            cur = tgt[0]
            roop += 1
    print(roop * ls + cur + 1)


if __name__ == "__main__":
    main()

Solution (Python):
import collections, bisect

s = input()
t = input()

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

m = len(t)
x = [0] * (m + 1) 
y = [0] * (m + 1) 

for i in range(1, m + 1):
    c = t[i - 1]
    if not c in d:
        print(-1)
        exit()
    
    a = y[i - 1]
    ptr = bisect.bisect_right(d[c], y[i - 1])
    if ptr == len(d[c]):
        b = d[c][0]
    else:
        b = d[c][ptr]
    
    y[i] = b
    if a < b:
        x[i] = x[i - 1] + b - a
    else:
        x[i] = x[i - 1] + n - a + b
    
print(x[-1])

Solution (Python):

from bisect import bisect_left as bs
from collections import defaultdict


def main():
    S, T = tuple(input() for _ in range(2))
    if not set(T) <= set(S):  
        print(-1)
        return
    idx, ls = defaultdict(list), len(S)
    for i, s in enumerate(S):
        idx[s] += [i]
    cur = -1
    for t in T:
        tgt = idx[t]
        x = (cur + 1) % ls
        i = bs(tgt, x)
        if i < len(tgt):
            cur += 1 + tgt[i] - x
        else:
            cur += 1 + tgt[0] - x + ls
    print(cur + 1)


if __name__ == "__main__":
    main()

Solution (Python):


import itertools
from collections import Counter
from collections import defaultdict
from collections import deque
import bisect
from heapq import heappush, heappop


def solve(positions, s, t):

    if not set(t) <= set(s):
        return -1

    loop = 0
    prev = -1

    for tchar in t:
        candidates = positions[tchar]
        pos = bisect.bisect_right(candidates, prev)

        if pos == len(candidates):
            loop += 1
            pos = 0
        prev = candidates[pos]

    return loop * len(s) + prev + 1


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

    positions = defaultdict(list)
    for i in range(len(s)):
        positions[s[i]].append(i)

    print(solve(positions, s, t))


if __name__ == '__main__':
    main()

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


def p_e():
    s = input()
    t = input()
    l = defaultdict(list)

    for i, c in enumerate(list(s)):
        l[c].append(i + 1)

    for c in list(t):
        if c not in l.keys():
            print(-1)
            exit()

    N = 0
    current = -1
    for c in list(t):
        R = l[c]

        x = bisect(R, current)

        if len(R) == x:
            N += 1
            current = R[0]
        else:
            current = R[x]

    print(N * len(s) + current)


if __name__ == '__main__':
    p_e()

Solution (Python):
import bisect
import sys

sys.setrecursionlimit(1000000)

s=input()
t=input()
dic={}
for v in s:
    dic[v]=True

for u in t:
    if not u in dic:
        print(-1)
        exit()

nex={}
for i, v in enumerate(s+s):
    if not v in nex:
        nex[v]=[i]
    else:
        nex[v].append(i)



sl=len(s)
tl=len(t)
def func(st, tn, su):
    if tn == tl:
        return su
    
    ind=bisect.bisect_left(nex[t[tn]] ,st+1)
    nm=(nex[t[tn]][ind]-st)
    return func((st+nm)%sl, tn+1, su+nm)


res=func(-1, 0, 0)

print(res)

Solution (Python):
import bisect
import re

s = input()
t = input()
sett = set(t)
sets = set(s)
for e in sett:
  if e not in sets:
    print(-1)
    exit()

sumidx = 0
tmps = s

s_dict = {}
count = 1
for e in sett:
  s_dict[e] = [m.start() for m in re.finditer(e, s)]
idx = 0
for e in t:
  l = s_dict[e]
  idx = bisect.bisect_left(l, idx)
  
  if idx == len(l):
    count += 1
    if count > 10 ** 100:
      print(-1)
      exit()
    sumidx += len(s)
    idx = l[0]+1
  else:
    
    idx = l[idx]+1
sumidx += idx
print(sumidx)

Solution (Python):
import bisect

def main():
    s = input()
    t = input()
    s_set = set(list(s))
    s_dict = {}
    s_len = len(s)
    t_list = list(t)
    t_set = set(t_list)
    c = -1
    ans = []
    ans_append = ans.append
    for i in s_set:
        s_dict[i] = []
    for i in range(s_len):
        s_dict[s[i]].append(i)
    if len(t_set) == len(t_set & s_set):
        for i in t_list:
            idxs = s_dict[i]
            if idxs[-1] <= c:
                c = idxs[0]
                ans_append(c)
            else:
                c = idxs[bisect.bisect(idxs,c)]
                ans_append(c)
        count = 0
        for i in range(len(ans)-1):
            if ans[i] >= ans[i+1]:
                count += 1
        print(s_len*count + ans[-1] + 1)
    else:
        print(-1)
    
if __name__ == '__main__':
    main()

Solution (Python):


import itertools
from collections import Counter
from collections import defaultdict
from collections import deque
import bisect
from heapq import heappush, heappop


def solve(positions, s, t):

    if not set(t) <= set(s):
        return -1

    loop = 0
    prev = -1

    for tchar in t:
        candidates = positions[tchar]
        pos = bisect.bisect_right(candidates, prev)

        if pos == len(candidates):
            loop += 1
            pos = 0
        prev = candidates[pos]

    return loop * len(s) + prev + 1


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

    positions = defaultdict(list)
    for i in range(len(s)):
        positions[s[i]].append(i)

    print(solve(positions, s, t))


if __name__ == '__main__':
    main()

Solution (Python):
import sys
from collections import defaultdict

def main():
    input = sys.stdin.readline
    S = str(input().strip())
    T = str(input().strip())

    if not set(T) <= set(S):
        return -1

    n = len(S)
    d = defaultdict(list)
    for i, s in enumerate(S, start=1):
        d[s].append(i)

    cnt = 0
    pos = 0
    for t in T:
        if pos >= d[t][-1]:
            cnt += 1
            pos = d[t][0]
        else:
            left = 0
            right = len(d[t])
            while left < right:
                mid = (left + right) // 2
                np = d[t][mid]
                if np <= pos:
                    left = mid + 1
                else:
                    right = mid
            pos = d[t][left]

    return n * cnt + pos


if __name__ == '__main__':
    print(main())

Solution (Python):
import sys
from collections import defaultdict

def main():
    input = sys.stdin.readline
    S = str(input().strip())
    T = str(input().strip())

    if not set(T) <= set(S):
        return -1

    n = len(S)
    d = defaultdict(list)
    for i, s in enumerate(S, start=1):
        d[s].append(i)

    cnt = 0
    pos = 0
    for t in T:
        if pos >= d[t][-1]:
            cnt += 1
            pos = d[t][0]
        else:
            left = 0
            right = len(d[t])
            while left < right:
                mid = (left + right) // 2
                np = d[t][mid]
                if np <= pos:
                    left = mid + 1
                else:
                    right = mid
            pos = d[t][left]

    return n * cnt + pos


if __name__ == '__main__':
    print(main())

Solution (Python):
import bisect

GG = [[] for i in range(26)]
L = [chr(i) for i in range(97, 123)]

s = input()
t = input()

N = len(s)
M = len(t)

for i in range(N):
	x = ord(s[i]) - 97
	GG[x].append(i)

for i in range(26):
	GG[i] = sorted(GG[i])


jud = [0] * 26
for i in range(26):
	if GG[i] != []:
		jud[i] = 1
j = "Y"
for i in range(M):
	if jud[ord(t[i]) - 97] == 0:
		j = "N"
		break

if j == "N":
	print(-1)
else:
	v = -1
	ans = 0
	for i in range(M):
		x = ord(t[i]) - 97
		y = bisect.bisect_right(GG[x], v)

		if y == len(GG[x]):
			z = GG[x][0]
		else:
			z = GG[x][y]
		if z <= v:
			ans += N
		v = z


	print(ans + v + 1)

Solution (Python):
s=input()
t=input()
leng=len(s)
lent=len(t)
count=0
tmp=0
i=0
while True:
   ans=s[tmp:].find(t[i])
   if ans!=-1:
       i += 1
       tmp += ans+1
       if i ==lent:
           count += tmp
           break
       continue
   if tmp==0:
       count=-1
       break
   tmp=0
   count+=leng
if count>leng*10**100:
    count=-1
print(count)

Solution (Python):
from bisect import bisect_right

s = list(input())
t = list(input())


pos_in_s = {}
for i in range(len(s)):
  c = s[i]
  if c not in pos_in_s:
    pos_in_s[c] = []
  pos_in_s[c].append(i)


pos = -1
rep = 0

for c in t:
  
  if c not in pos_in_s:
    pos = -1
    break
    
  
  right = bisect_right(pos_in_s[c], pos)
  if right == len(pos_in_s[c]):
    pos = pos_in_s[c][0]
    rep += 1
  else:
    pos = pos_in_s[c][right]
    

if pos == -1:
   print(-1)
else:
  print(rep * len(s) + pos + 1)

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

dic = {}
for i in range(len(s)):
    c = s[i]
    if c not in dic:
        dic[c] = []
    dic[c].append(i)

repeat = 0
focus = 0
ans = 0
for i in range(len(t)):
    c = t[i]
    if c not in dic:
        ans = -1
        break
    if dic[c][-1] < focus:
        repeat += 1
        focus = dic[c][0]+1
    else:
        l = 0
        r = len(dic[c])
        while l < r:
            mid = (r+l)//2
            if(dic[c][mid] < focus):
                l = mid + 1
            else:
                r = mid
        focus = dic[c][l]+1
print(ans if ans == -1 else repeat*len(s)+focus)

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

next_map = sorted(zip(s*2,range(N*2)))
br = bisect.bisect_right
ans = 0
i = -1
for c in t:
    map_idx = br(next_map,(c,i))
    if map_idx == N*2:
        ans = -1
        break
    a,j = next_map[map_idx]
    if a != c :
        ans = -1
        break
    ans += j - i
    i = j%N
print(ans)

Solution (Python):
s=input()
t=input()
n=0
c=0
for e in t:
    try:
        i=s[c:].index(e)
        n+=i+1
        c=(c+i+1)%len(s)
    except ValueError:
        try:
            i=s.index(e)
            n+=len(s)-c+i+1
            c=i+1
        except ValueError:
            n=-1
            break
print(n)

Solution (Python):
import sys

ordA = ord('a')

ss = input()
ts = input()

lenS, lenT = len(ss), len(ts)

setS = set(ss)
for t in ts:
    if t not in setS:
        print(-1)
        sys.exit()

poss = [-1] * 26
for i, s in enumerate(ss):
    ch = ord(s)-ordA
    if poss[ch] == -1:
        poss[ch] = i + lenS

nextss = [[0]*(26) for _ in range(lenS)]
for i in reversed(range(lenS)):
    ch = ord(ss[i])-ordA
    poss[ch] = i
    for ch, pos in enumerate(poss):
        nextss[i][ch] = pos-i

i = 0
ans = 1
for t in ts:
    ch = ord(t)-ordA
    d = nextss[i][ch]
    ans += d+1
    i = (i+d+1) % lenS

print(ans-1)

Solution (Python):
import bisect
s = input()
t = input()
lens=len(s)
lent=len(t)
d = {}
s2=s+s
lens2=len(s2)

for i in range(lens2):
    if s2[i] in d:
        d[s2[i]].append(i)
    else:
        d[s2[i]] = [i]

tmp=0
r=0
snum=0
for i in range(lent):
    if(lens<tmp):
        snum+=lens
        tmp-=lens
        
    if d.get(t[i],None)==None:
        print("-1")
        exit()
    else:
        lis=d[t[i]]
        r = bisect.bisect_left(lis,tmp)
        tmp=lis[r]+1
print(snum+tmp)

Solution (Python):
import string
import bisect

S, T = input(), input()
lS, lT = len(S), len(T)

l = {s: [] for s in string.ascii_lowercase}
for i in range(lS):
    l[S[i]].append(i)

id, ans = -1, 0
for i in range(lT):
    if len(l[T[i]]) == 0:
        print(-1)
        exit()

    tmp = l[T[i]][(bisect.bisect(l[T[i]], id)) % len(l[T[i]])]
    if id >= tmp:
        ans += lS
    id = tmp

print(ans + id + 1)

Solution (Python):
from collections import*
from bisect import*
s=input()
n=len(s)
t=input()
d=defaultdict(list)
for i,c in enumerate(s):
    d[c].append(i)
m=-1
o=0
for c in t:
    if not d[c]:
        print(-1)
        exit()
    i=bisect(d[c],m)
    if len(d[c])==i:
        o+=1
        m=d[c][0]
    else:
        m=d[c][i]
print(o*n+m+1)

Solution (Python):
from bisect import bisect
s = input()
t = input()
def ctoi(c):
	return ord(c) - ord("a")
if not (set(s) >= set(t)):
	print(-1)
else:
	alph = [[] for _ in range(26)]
	for i in range(len(s)):
		alph[ctoi(s[i])].append(i)
	for a in alph:
		if a:
			a.append(a[0] + len(s))
	cur = len(s)-1
	ans = 0
	for i in range(len(t)):
		ind = bisect(alph[ctoi(t[i])], cur)
		ans += alph[ctoi(t[i])][ind] - cur
		cur = alph[ctoi(t[i])][ind] % len(s)
	print(ans)

Solution (Python):
from collections import defaultdict as dd
from bisect import bisect_left as bl
s = input()
t = input()
ind = dd(list)
res = 0
first = 1
for i in range(len(s)):
  ind[s[i]].append(i)

for i in range(len(t)):
  if len(ind[t[i]]) == 0:
    print(-1)
    exit(0)
  temp = bl(ind[t[i]], res % len(s))
  
  if first == 0:
    if res % len(s) == ind[t[i]][min(temp, len(ind[t[i]]) - 1)]:
      temp += 1
  first = 0
  if temp == len(ind[t[i]]):
    res += (len(s) - res % len(s)) + ind[t[i]][0]
  else:
    res += ind[t[i]][temp] - res % len(s)
print(res + 1)

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

if __name__ == "__main__":
    n = len(S)
    ans = 0
    pre = -1 
    for c in T: 
        pos = S.find(c, pre + 1, n)
        if pos != -1:
            ans += (pos - pre)
            pre = pos 
        else:
            pos = S.find(c, 0, pre + 1)
            if pos != -1:
                ans += n + pos - pre
                pre = pos  
            else:
                ans = -1
                break
    
    print(ans)

Solution (Python):
import numpy as np
import math
import sys
import bisect
sys.setrecursionlimit(10000000)

def main():
    s = input()
    t = input()
    alphabets = dict.fromkeys(list("abcdefghijklmnopqrstuvwxyz"), None)
    
    for key_ in alphabets:
        lists = []
        for i in range(len(s)):
            if key_ == s[i]:
                lists.append(i)
        alphabets[key_] = lists
    now = -1
    count = 0
    for alpha in t:
        if len(alphabets[alpha]) == 0:
            print(-1)
            sys.exit()
        else:
            lists = alphabets[alpha]
            index = bisect.bisect_right(lists, now)
            if index >= len(lists):
                now = -1
                count += len(s)
                now = lists[0]
            else:
                now = lists[index]
            
    print(count + now + 1)
            







if __name__ == '__main__':
    main()

Solution (Python):
import bisect
S=input()
T=input()
N=len(S)
M=len(T)
chardict=dict()
for i in range(26):
    chardict[chr(i+97)]=[]
for i in range(2*N):
    chardict[S[i%N]].append(i)
dp=[0 for i in range(M+1)]
dp[0]=-1
for i in range(M):
    nowpoint=dp[i]%N
    cycle=dp[i]//N
    
    if len(chardict[T[i]])==0:
        print(-1)
        exit()
    tmp=bisect.bisect_right(chardict[T[i]],nowpoint)
    dp[i+1]=cycle*N+chardict[T[i]][tmp]
print(dp[M]+1)

Solution (Python):
import bisect

S = list(input())
T = list(input())

s_dic = {}
for i,s in enumerate(S):
    if s not in s_dic.keys():
        s_dic[s] = [i]
    else:
        s_dic[s].append(i)

def main():
    pre, n_repeat = -1, 0
    cur = -1
    for t in T:
        if t not in s_dic.keys():
            return -1
        i = bisect.bisect_right(s_dic[t], cur)
        if i >= len(s_dic[t]):
            cur = s_dic[t][0]
            n_repeat += 1
        else:
            cur = s_dic[t][i]
            if cur <= pre:
                n_repeat += 1
        pre = cur
            
    return n_repeat * len(S) + cur + 1

print(main())

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

def main():
    s = SI()
    t = SI()

    import collections
    d = collections.defaultdict(list)
    for i, c in enumerate(s):
        d[c].append(i)

    keys = d.keys()
    for c in set(t):
        if c not in keys:
            print(-1)
            return

    import bisect

    i_loop = 0
    currentidx = -1
    for c in t:
        
        poslist = d[c]

        
        posidx = bisect.bisect_right(poslist, currentidx)

        if posidx >= len(poslist):
            
            i_loop += 1
            currentidx = poslist[0]
        else:
            
            pos = poslist[posidx]
            currentidx = pos

    print(len(s)*i_loop + currentidx + 1)

main()

Solution (Python):
import bisect

s = input()
t = input()
s_length = len(s)
t_length = len(t)

def char2int(char):
    return ord(char) - 97

def search_index(t_atom, last_index, d_list):
    t_atom_int = char2int(t_atom)
    d = d_list[t_atom_int]

    if d == []:
        return -1

    c = bisect.bisect_right(d, last_index)

    if c != len(d):
        return d[c]
    else:
        return d[0]

def solve():
    last_index = -1
    t_index = []
    loop_cost = 1

    d = [[] for _ in range(26)]
    for i in range(s_length):
        char = s[i]
        d[char2int(char)].append(i)

    for i in range(t_length):
        t_atom = t[i]
        t_atom_index = search_index(t_atom, last_index, d)
        if t_atom_index == -1:
            return -1
        else:
            t_index.append(t_atom_index)
            last_index = t_atom_index

    remainder_cost = t_index[-1] + 1

    for i in range(1, t_length):
        if t_index[i - 1] >= t_index[i]:
            loop_cost += 1

    return s_length * (loop_cost - 1) + remainder_cost

print(solve())

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):
S = input()
T = input()

length = len(S)

ans = 0
pre = -1

for t in T:
    x = S.find(t, pre+1, length)
    if x != -1:
        ans += x - pre
        pre = x
    else:
        x = S.find(t, 0, pre+1)
        if x != -1:
            ans += length + x - pre
            pre = x
        else:
            ans = -1
            break

print(ans)

Solution (Python):


from bisect import bisect_left

s = input()
t = input()

if not set(t) <= set(s):
    print(-1)
    exit()

s_dict = {}
for i in range(len(s)):
    c = s[i]
    if c not in s_dict.keys():
        s_dict[c] = [i]
    else:
        s_dict[c].append(i)

repeat = 0
s_idx = 0
for c in t:
    idx = bisect_left(s_dict[c], s_idx)
    if idx == len(s_dict[c]):
        s_idx = s_dict[c][0] + 1
        repeat += 1
    else:
        s_idx = s_dict[c][idx] + 1
else:
    ans = repeat * len(s) + s_idx

print(ans)

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

flag = 0
count = 0
rest_s = s
n = len(s)

for w in t:
  if w not in s:
    flag = 1
    print(-1)
    break

if flag == 0:
  for w in t:
    index = rest_s.find(w)
    
    if (index != -1):
      if (rest_s != s):
        count += (index+1)
      else:
        count += (index)
      rest_s = s[count%n+1:]
    else:
      index = s.find(w)
      count = (count // n + 1) * n + index
      rest_s = s[count%n+1:]
    
  print(count+1)

Solution (Python):

def main():
    S, T = tuple(input() for _ in range(2))
    if not set(T) <= set(S):  
        print(-1)
        return
    ans, cur, idx, lim = 1, 0, -1, len(T)
    while cur < lim:
        find = S[idx + 1:].find(T[cur])
        if find == -1:
            ans += 1
            idx = -1
        else:
            idx += find + 1
            cur += 1
    ans = (ans - 1) * len(S) + idx + 1
    print(ans)


if __name__ == "__main__":
    main()

Solution (Python):
import bisect as bs
s=input()
t=input()
ss={}
ind={}
j=0
for i in s:
    try:
        ss[i].append(j)
    except:
        ss[i]=[j]
        ind[i]=0
    j+=1
c=0
st=False
for i in t:
    try:
        x=ss[i]
    except:
        st=True
        break
if st:
    print(-1)
else:
    p=-1
    for i in t:
        x=bs.bisect_right(ss[i],p)
   
        try:
            p=ss[i][x]
    
        except:
     
            c+=1
            p=ss[i][0]
    tot=c*len(s)
    if p!=-1:
        tot+=p+1
    print(tot)

Solution (Python):
import sys
sys.setrecursionlimit(10**7)
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x) - 1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def II(): return int(sys.stdin.readline())
def SI(): return sys.stdin.readline().strip()
INF = 10 ** 18
MOD = 10 ** 9 + 7

def main(): 
    s = SI()
    t = SI()

    from collections import defaultdict
    s_dict = defaultdict(list)
    for i, char in enumerate(s):
        s_dict[char].append(i)

    

    from bisect import bisect, bisect_left

    current_position = 0
    s_loops = 0
    first = True
    for char in t:
        li = s_dict[char]
        if not li:
            print(-1)
            return
        if first:  
            first = False
            current_position = li[0]
        else:
            
            
            pos = bisect_left(li, current_position)
            try:
                if li[pos] == current_position:
                    current_position = li[pos+1]
                else:
                    current_position = li[pos]
            except IndexError:
                
                s_loops += 1
                current_position = li[0]

    print(len(s)*s_loops + current_position+1)



main()

Solution (Python):
import bisect as bs

def main():
	s = input()
	t = input()
	indx = [[] for _ in range(26)]
	count = [0 for _ in range(26)]
	loop = 0
	pre = -1
	lens = len(s)
	for i in range(lens):
		c = ord(s[i])-97
		indx[c] += [i]
		count[c] += 1
	for i in range(len(t)):
		c = ord(t[i])-97
		if indx[c] == []:
			print(-1)
			return
		ref = bs.bisect(indx[c],pre)
		if indx[c][ref%count[c]] <= pre:
			loop += 1
		pre = indx[c][ref%count[c]]
		
	print(loop*lens + pre + 1)

main()

Solution (Python):
import decimal,math
from collections import Counter,defaultdict
from fractions import gcd
from bisect import bisect_right,bisect_left
decimal.getcontext().prec = 10
s=raw_input()
t=raw_input()
index={}
for i in range(len(s)):
	if(index.get(s[i])):
		index[s[i]].append(i)
	else:
		index[s[i]]=[i]	
flag=0
for i in t:
	if(index.get(i)):
		continue
	else:
		flag=1
		break
if(flag==1):
	print -1
	exit()		
ans=len(s)
co=0
bad=0
arrr = [index[t[0]][0]]



for i in range(1,len(t)):
	o = index[t[i]]
	l = bisect_right(o,arrr[-1])
	
	if(l>=len(o)):
		arrr.append(o[0])
		
	else:
		arrr.append(o[l])	

for i in range(1,len(arrr)):
	if(arrr[i]<=arrr[i-1]):
		ans=ans+len(s)
print ans-(len(s)-arrr[-1]-1)

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

S = input()
S_set = set(S)
d = defaultdict(list)
for i,s in enumerate(S):
    d[s].append(i)


T = input()
T_set = set(T)
for t in T_set:
    if t not in S_set:
        print(-1)
        exit()

cnt = 0
loop = 0
prev = -1

for t in T:
    num = d[t]
    a = bisect_right(num,prev)
    
    
    if a >= len(num):
        loop += 1
        a = 0
    prev = num[a]

print(prev+1+(loop)*len(S))

Solution (Python):
import sys
import bisect
MAX_INT = int(10e10)
MIN_INT = -MAX_INT
mod = 1000000007
sys.setrecursionlimit(1000000)
def IL(): return list(map(int,input().split()))
def SL(): return input().split()
def I(): return int(sys.stdin.readline())
def S(): return input()

s = S()
t = S()
N = len(s)

dic = {}

for i in range(N):
  if s[i] in dic:
    dic[s[i]].append(i+1)
  else:
    dic[s[i]] = [i+1]

tmp = 0
cnt = 0
for i in t:
  if i not in dic:
    print(-1)
    exit()
  else:
    l = dic[i]
    n = bisect.bisect_left(l,tmp)
    if n > len(l)-1:
      tmp = l[0]
      cnt += 1
    else:
      if tmp == l[n]:
        n += 1
        if n > len(l)-1:
          tmp = l[0]
          cnt += 1
        else:
          tmp = l[n]
      else:
        tmp = l[n]

print(cnt*N+tmp)

Solution (Python):
s=input()
t=input()
set_s = {x for x in s}
set_t = {x for x in t}
if len(set_t-set_s)>0:
    print(-1)
else:
    n=len(s)
    letters='abcdefghijklmnopqrstuvwxyz'
    l=[[-1 for i in range(n)] for j in range(26)]
    for i in range(26):
        letter = letters[i]
        if s[-1]==letter:
            l[i][-1]=n-1
        for j in range(1,n):
            idx=n-1-j
            if s[idx]==letter:
                l[i][idx]=idx
            else:
                l[i][idx]=l[i][idx+1]
    cnt=1
    a=0
    for x in t:
        id = ord(x)-97
        if a>=n or l[id][a]==-1:
            cnt+=1
            a=0
            a=l[id][a]+1
        else:
            a=l[id][a]+1
    print((cnt-1)*n+a)

Solution (Python):
s = input()
t = input()
from collections import defaultdict
from bisect import bisect_left
d = defaultdict(list)
for i, e in enumerate(s):
  d[e].append(i)

for e in t:
  if e not in d:
    print(-1)
    exit()
cur = -1
loop = 0
for e in t:
  idxt = bisect_left(d[e], cur-loop*len(s)+1)
  
  if len(d[e])>idxt:
    
    idx = d[e][idxt]
    cur = (loop*len(s))+idx
    
  else:
    loop += 1
    idxt = bisect_left(d[e], cur-loop*len(s)+1)
    
    idx = d[e][idxt]
    cur = (loop*len(s))+idx
  
print(cur+1)

Solution (Python):
import bisect

s = input()
t = input()

if set(list(t)).issubset(set(list(s))):
    index_list = [ [] for i in range(26) ]
    for i, v in enumerate(s,1):
        index_list[ord(v)-97].append(i)
    ls = len(s)
    for i in range(26):
        index_list[i].append(ls+1)

    old_index = 0
    index = 0
    turn = 0 
    for i, v in enumerate(t):

        new_index = bisect.bisect_left(index_list[ord(v)-97],index+1)
        index = index_list[ord(v)-97][new_index]

        

        if index == ls+1:
            new_index = bisect.bisect_left(index_list[ord(v)-97],0)
            index = index_list[ord(v)-97][new_index]
            turn += 1


    print(index+turn*ls)

else:
    print(-1)

Solution (Python):
def main():
    from collections import defaultdict
    import sys
    
    s = input()
    t = input()
    ds = defaultdict(int)
    di = {}

    for i in range(len(s)):
        di[i] = defaultdict(int)
    
    for a in s:
        ds[a] = 1
        
    flag = 0
    for b in t:
        if ds[b] == 0:
            flag = 1
    if flag == 1:
        print(-1)
        sys.exit()

    s2 = s[::-1]
    for i in range(2*len(s)):
        for j in di[len(s) - (i-1)%len(s)-1]:
            di[len(s) - i%len(s)-1][j] = di[len(s) - (i-1)%len(s)-1][j] + 1
        di[len(s) - i%len(s) - 1][s2[(i-1)%len(s)]] = 1
    tmp = t[0]

    for k in range(len(s)):
        if tmp == s[k]:
            answer = k+1
            break
    for k in range(len(t)-1):
        l = k+1
        answer += di[(answer-1)%len(s)][t[l]]
        tmp = t[l]
    print(answer)
      

if __name__ == '__main__':
    main()

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

if not set(t) <= set(s):
    print(-1)
    exit()

inds = defaultdict(list)
inds_cnt = defaultdict(int)

for i in range(len(s)):
    inds[s[i]].append(i)
for i in range(97,97+26):
    inds_cnt[chr(i)] = len(inds[chr(i)])

k = 0
ans = 0
N = len(s)

for c in t:
    j = bisect_left(inds[c],k)
    if j == inds_cnt[c]:
        k = inds[c][0] + 1
        ans+=N
    else:
        k=inds[c][j] + 1
print(ans+k)

Solution (Python):
from sys import stdin,stdout
I = lambda : map(int,stdin.readline().split())

alphabet = [chr(x) for x in range(ord('a'), ord('z')+1)]
alnum = lambda x: ord(x) - ord('a')


def next(i, n):
	return (i+1) % n
def prev(i, n):
	return (i-1+n) % n

def next_arr(ch, a):
	n = len(a)
	i = a.find(ch)
	if i == -1:
		return [-1] * n
	ret = [-1] * n
	while ret[prev(i,n)] == -1:
		if a[i] == ch:
			ret[prev(i,n)] = i
		else:
			ret[prev(i,n)] = ret[i]
		i = prev(i,n)
	return ret

a = raw_input()
b = raw_input()
n = len(a)

next_ = [next_arr(alphabet[i], a) for i in range(26)]
ptr = -1
ans = 0
for ch in b:
	old_ptr = ptr
	ptr = next_[alnum(ch)][ptr]
	if ptr == -1:
		print -1
		exit()
	if ptr <= old_ptr:
		ans += n
print ans+ptr+1