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):
s = input()
n = len(s)
l = [[]for i in range(26)]

for i, c in enumerate(s * 2):
    l[ord(c) - ord('a')].append(i)


from bisect import *

shukai = 0
now = 0

t = input()
for c in t:
    x = ord(c) - ord('a')
    if len(l[x]) == 0:
        print(-1)
        exit()
    i = bisect_left(l[x], now)
    now = l[x][i] + 1

    if now >= n:
        now -= n
        shukai += 1


print(shukai * n + now)

Solution (Python):
import bisect
s = input()
t = input()
d = {}
if set(t) <= set(s):
    for c in set(s):
        d[c] = []
    for i,c in enumerate(s):
        d[c].append(i)
    ret = 0
    for i,c in enumerate(t):
        if i==0:
            loc = d[t[0]][0]
        else:
            nx_idx = bisect.bisect_right(d[c], loc)
            if nx_idx == len(d[c]):
                ret += 1
                nx_idx = 0
            nx_loc = d[c][nx_idx]
            loc = nx_loc
    print(ret*len(s) + loc + 1)
else:
    print(-1)

Solution (Python):
import bisect
s = list(input())
t = list(input())
dic = {}
for i, j in enumerate(s):
    if j in dic:
        dic[j].append(i)
    else:
        dic[j] = [i]
loop = 0
if set(t) <= set(s):
    for i in range(len(t)):
        if i==0:
            idx = dic[t[0]][0]
        else:
            lis = dic[t[i]]
            idx2 = bisect.bisect_right(lis, idx)
            if idx2 == len(lis):
                loop += 1
                idx = lis[0]
            else:
                idx = lis[idx2]
    print(loop*len(s) + idx + 1)
else:
    print(-1)

Solution (Python):
import bisect

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

dic = {}
for i, j in enumerate(s):
    if j in dic:
        dic[j].append(i)

    else:
        dic[j] = [i]

loop = 0
try:
    for i in range(len(t)):
        if i == 0:
            idx = dic[t[0]][0]

        else:
            lis = dic[t[i]]
            idx2 = bisect.bisect_right(lis, idx)
            if idx2 == len(lis):
                loop += 1
                idx = lis[0]

            else:
                idx = lis[idx2]
    

    print(len(s) * loop + idx + 1)
except:
    print(-1)

Solution (Python):
from bisect import bisect_left
s = input()
t = input()
dic = {}
for ind, c in enumerate(s):
    if c in dic:
        dic[c].append(ind)
    else:
        dic[c] = [ind]
loop = 0
ind = 0
try:
    for c in t:
        if ind > dic[c][-1]:
            ind = dic[c][0] + 1
            loop += 1
            continue
        tmp = bisect_left(dic[c], ind)
        ind = dic[c][tmp] + 1
    print(len(s)*loop+ind)
except:
    print(-1)

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

sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

S = sr()
T = sr()
S_set = set(S)
T_set = set(T)
if len(T_set - S_set) > 0:
    print(-1); exit()


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

cur = -1
lenS = len(S)
answer = 0
for t in T:
    cur += 1
    answer += 1
    L = dict_S[t]
    i = bisect_left(L, cur)
    if i == len(L):
        answer += lenS - cur + L[0]
        cur = L[0]
    else:
        answer += L[i] - cur
        cur = L[i]

print(answer)

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

sdict = {}
for i,c in enumerate(s):
    if c not in sdict:
        sdict[c] = []
    sdict[c].append(i)

ans = 0
spos = -1
for c in t:
    if c not in sdict:
        print(-1)
        exit()
    tt = bisect_right(sdict[c], spos)
    if tt == len(sdict[c]):
        
        tt = bisect_right(sdict[c], -1)
        ans += len(s)
    
    spos = sdict[c][tt]

print(ans + spos + 1)

Solution (Python):
import bisect
from collections import defaultdict

S=list(input().strip())
T=list(input().strip())
L=len(S)

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

d=defaultdict(list)
for i,s in enumerate(S):
  d[s].append(i)
start=-1
ans=0
for i in T:
  p=bisect.bisect_right(d[i],start)
  le=len(d[i])
  if p==le:
    ans+=(L-start-1)+(d[i][0]+1)
    start=d[i][0]    
  else:
    ans+=d[i][p]-start
    start=d[i][p]
print(ans)

Solution (Python):

from bisect import bisect_left, bisect_right

s = input()
t = input()
if set(s) >= set(t):
    al_idx = [[] for _ in range(26)]
    ss = s * 2
    alp = 'abcdefghijklmnopqrstuvwxyz'
    for i in range(len(ss)):
        al_idx[alp.index(ss[i])].append(i)
    
    tmp = -1
    ans = 0
    for j in range(len(t)):
        idx = alp.index(t[j])
        cur = bisect_right(al_idx[idx], tmp)
        ans += al_idx[idx][cur] - tmp
        tmp = al_idx[idx][cur] % len(s)
        
    print(ans)
else:
    print(-1)

Solution (Python):

import math
import bisect












s=input()
t=input()

alpha=list("abcdefghijklmnopqrstuvwxyz")

dic_s={alpha[i]:0 for i in range(26)}
dic_t={alpha[i]:0 for i in range(26)}

a={alpha[i]:[] for i in range(26)}
b={alpha[i]:[] for i in range(26)}


for i in range(len(s)):
  
    if dic_s[s[i]]==0:
        dic_s[s[i]]=+1
    a[s[i]].append(i+1)


for j in range(len(t)):
    
    if dic_t[t[j]]==0:
        dic_t[t[j]]=+1
    b[t[j]].append(j+1)
for i in range(26):
	a[alpha[i]].append(10**9)
flag=True

for i in range(26):
    if dic_t[alpha[i]]>0 and dic_s[alpha[i]]==0:
        flag=False

place=[0,0]

if flag:
    
    for i in range(len(t)):
        string=t[i]
        num=bisect.bisect_right(a[string],place[0])  
        if a[string][num]==10**9:
            place[1]+=1
            place[0]=a[string][0]
        else:
            place[0]=a[string][num]
  

    print(place[0]+place[1]*len(s))

else:
    
    print(-1)

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

s = input().rstrip()
t = input().rstrip()
n = len(s)
m = len(t)

from collections import deque

dic = {}
for i in range(ord("a"), ord("z") + 1):
    dic[chr(i)] = deque([])


for i in range(n):
    dic[s[i]].append(i + 1)

cnt = 0
res = 0
from bisect import bisect

for i in t:
    if len(dic[i]) == 0:
        print(-1)
        sys.exit()
    idx = bisect(dic[i], cnt)
    if idx >= len(dic[i]):
        res += 1
        cnt = dic[i][0]
    else:
        cnt = dic[i][idx]

print(n * res + cnt)

Solution (Python):

import math
import bisect












s=input()
t=input()

alpha=list("abcdefghijklmnopqrstuvwxyz")

dic_s={alpha[i]:0 for i in range(26)}
dic_t={alpha[i]:0 for i in range(26)}

a={alpha[i]:[] for i in range(26)}
b={alpha[i]:[] for i in range(26)}


for i in range(len(s)):
  
    if dic_s[s[i]]==0:
        dic_s[s[i]]=+1
    a[s[i]].append(i+1)


for j in range(len(t)):
    
    if dic_t[t[j]]==0:
        dic_t[t[j]]=+1
    b[t[j]].append(j+1)
for i in range(26):
	a[alpha[i]].append(10**9)
flag=True

for i in range(26):
    if dic_t[alpha[i]]>0 and dic_s[alpha[i]]==0:
        flag=False

place=[0,0]

if flag:
    
    for i in range(len(t)):
        string=t[i]
        num=bisect.bisect_right(a[string],place[0])  
        if a[string][num]==10**9:
            place[1]+=1
            place[0]=a[string][0]
        else:
            place[0]=a[string][num]
  

    print(place[0]+place[1]*len(s))

else:
    
    print(-1)

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

alph = "abcdefghijklmnopqrstuvwxyz"
to_int = {char: i for i, char in enumerate(alph)}

set_ = set(list(s))
for char in t:
    if char not in set_:
        print(-1)
        exit()

next_ = [[0] * 26 for i in range(n + 1)]
for i in range(n)[::-1]:
    for j, char in enumerate(alph):
        if s[i] == char:
            next_[i][j] = i + 1
        else:
            next_[i][j] = next_[i + 1][j]

ans = 0
pos = 0
for char in t:
    if next_[pos][to_int[char]] == 0:
        ans += len(s)
        pos = next_[0][to_int[char]]
    else:
        pos = next_[pos][to_int[char]]
print(ans + pos)

Solution (Python):
import bisect
s = input()
t = input()
sub = s+s
dp = []
for i in range(len(s)):
    d = [10**15]*26
    dp.append(d)
index = [[] for i in range(26)]
for i in range(len(sub)):
    index[ord(sub[i])-97].append(i)
for i in range(len(s)):
    cur = s[i]
    for j in range(26):
        if len(index[j]) != 0:
            k = bisect.bisect_right(index[j], i)
            dp[i][j] = index[j][k]-i
if s[0] == t[0]:
    ans = 1
else:
    ans = dp[0][ord(t[0])-97]+1
if dp[0][ord(t[0])-97] != 10**15 and dp[0][ord(t[0])-97] >= len(s):
    next = dp[0][ord(t[0])-97]-len(s)
else:
    next = dp[0][ord(t[0])-97]
if next == 10**15:
    print(-1)
    exit()
else:
    flag = True
for i in range(1,len(t)):
    cur = next
    if dp[cur][ord(t[i])-97] == 10**15:
        flag = False
        break
    else:
        ans += dp[cur][ord(t[i])-97]
        if cur + dp[cur][ord(t[i])-97] >= len(s):
            next = cur + dp[cur][ord(t[i])-97] - len(s)
        else:
            next = cur + dp[cur][ord(t[i])-97]
if flag:
    print(ans)
else:
    print(-1)

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

import bisect
from collections import defaultdict
d = defaultdict(list)
for i in range(len(s)):
    d[s[i]].append(i)


now=-1
cnt=0
for i in range(len(t)):
    if len(d[t[i]])==0:
        print(-1)
        exit()

    ind = bisect.bisect_right(d[t[i]],now)

    if ind==len(d[t[i]]):
        ind = bisect.bisect_right(d[t],0)
        cnt+=1

    now=d[t[i]][ind]

print(cnt*len(s) +now +1)

Solution (Python):
from bisect import bisect_right
def main():
  s=input()
  t=input()
  n=len(t)
  m=len(s)
  lindex=[[] for _ in range(26)]
  for i in range(m):
    if s[i] in t:
      lindex[ord(s[i])-97].append(i)
  for i in range(n):
    if len(lindex[ord(t[i])-97])==0:
      print(-1)
      exit()
  cnt=0
  inde=-1
  for i in range(n):
    l=len(lindex[ord(t[i])-97])
    idx=bisect_right(lindex[ord(t[i])-97],inde)
    if l==idx:
      cnt+=1
      inde=lindex[ord(t[i])-97][0]
    else:
      inde=lindex[ord(t[i])-97][idx]
  return print(m*cnt+inde+1)
if __name__=='__main__':
  main()

Solution (Python):
import sys

input = sys.stdin.buffer.readline






from collections import defaultdict
import bisect

def main():
	s=input().rstrip().decode('utf-8')
	t=input().rstrip().decode('utf-8')

	D=defaultdict(list)

	for i in range(len(s)):
		D[s[i]].append(i+1)

	now=0
	cnt=0

	for i in t:
		if D[i]==[]:
			print(-1)
			exit(0)
		else:
			idx=bisect.bisect_right(D[i],now)
			try:
				now=D[i][idx]
			except:
				now=D[i][0]
				cnt+=1
	print(cnt*len(s)+now)
















if __name__ == "__main__":
	main()

Solution (Python):
import sys
import bisect
def main():
    input = sys.stdin.readline
    s = input().rstrip()
    t = input().rstrip()

    letters = set(t)
    indices = dict()
    for l in letters:
        lst = []
        left = 0
        while left < len(s):
            i = s.find(l, left)
            if i < 0: break
            lst.append(i)
            left = i+1
        if not lst:
            print(-1)
            exit()
        indices[l] = lst
    
    offset = 0
    cycle = 0
    for l in t:
        ind = indices[l]
        i = bisect.bisect_left(ind, offset)
        if i < len(ind):
            offset = ind[i] + 1
        else:
            offset = ind[0] + 1
            cycle += 1
        if offset >= len(s):
            offset %= len(s)
            cycle += 1

    print(len(s)*cycle + offset)

if __name__ == '__main__':
    main()

Solution (Python):
from collections import defaultdict
import bisect

S = input()
T = input()

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

ans = 0
i = 0

for t in T:
    if not d[t]:
        print(-1)
        exit()

    if i >= d[t][-1]:
        ans += len(S)
        i = d[t][0]
        continue

    pos = bisect.bisect_right(d[t], i)
    i = d[t][pos]

ans += i
print(ans)

Solution (Python):
from bisect import bisect_left

s = input()
t = input()
idx = [[] for _ in range(26)]
for i in range(len(s)):
    c = ord(s[i]) - ord('a')
    idx[c].append(i)
count = 0
index = -1
for i in range(len(t)):
    c = ord(t[i]) - ord('a')
    if len(idx[c]) == 0:
        print(-1)
        exit()
    j = bisect_left(idx[c], index+1)
    if j == len(idx[c]):
        count += 1
        index = idx[c][0]
    else:
        index = idx[c][j]
print(count*len(s) + index + 1)

Solution (Python):
s=input()
t=input()
ls,lt=len(s),len(t)
if not set(t)<=set(s):print(-1);exit()
co=0
ind=-1
for i in range(lt):
  ind=s.find(t[i],ind+1)
  if ind==-1:
    ind=s.find(t[i])
    co+=1
print(co*ls+ind+1)

Solution (Python):
import bisect
from collections import defaultdict


S = list(input().strip())
T = list(input().strip())
L = len(S)

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

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

idx = -1
ans = 0
for t in T:
    pos = bisect.bisect_right(d[t], idx)
    if pos == len(d[t]):
        ans += L - idx - 1 + d[t][0] + 1
        idx = d[t][0]
    else:
        ans += d[t][pos] - idx
        idx = d[t][pos]

print(ans)

Solution (Python):
from bisect import bisect_left

s = input()
t = input()

l = len(s)

ss = s * 2
let = [[] for _ in range(26)]
for i, e in enumerate(ss, 1):
    idx = ord(e) - ord("a")
    let[idx].append(i)

for e in t:
    idx = ord(e) - ord("a")
    if not let[idx]:
        print(-1)
        exit()

i = 1
times = 0
for e in t:
    j = ord(e) - ord("a")
    choose = bisect_left(let[j], i)
    q, r = divmod(let[j][choose], l)
    times += q
    i = r + 1

ans = times * l + i - 1
print(ans)

Solution (Python):
from bisect import bisect_left

s = input()
t = input()

l = len(s)

ss = s * 2
let = [[] for _ in range(26)]
for i, e in enumerate(ss, 1):
    idx = ord(e) - ord("a")
    let[idx].append(i)

for e in t:
    idx = ord(e) - ord("a")
    if not let[idx]:
        print(-1)
        exit()

i = 1
times = 0
for e in t:
    j = ord(e) - ord("a")
    choose = bisect_left(let[j], i)
    q, r = divmod(let[j][choose], l)
    times += q
    i = r + 1

ans = times * l + i - 1
print(ans)

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

dic = {chr(s): [] for s in range(ord("a"), ord("z") + 1)}
for i, s in enumerate(S):
    dic[s].append(i + 1)

out = 0
cnt = -1
V = [0] * len(T)
for i, t in enumerate(T):
    if dic[t]:
        """
        for l in dic[t]:
            if cnt < l:
                V[i] = l
                cnt = l
                break
        else:
            cnt = dic[t][0]
        """

        idx = bisect.bisect(dic[t], cnt)
        if idx == len(dic[t]):
            V[i] = dic[t][0]
            cnt = dic[t][0]
        else:
            V[i] = dic[t][idx]
            cnt = dic[t][idx]

    else:
        out = 1
        break
if out == 1:
    print(-1)
else:
    cnt = 0
    for i in range(len(V)-1):
        if V[i+1] <= V[i]:
            cnt += 1
    if cnt == 0:
        print(V[-1])
    elif V[-1] == len(S):
        print(len(S) * (cnt + 1))
    else:
        print(len(S) * cnt + V[-1])
a = 0

Solution (Python):
import string
import bisect

s = str(input())
t = str(input())
len_s = len(s)
len_t = len(t)

s_alpha_ind = {x:[] for x in string.ascii_lowercase}

for i in range(len_s):
    s_alpha_ind[s[i]].append(i+1)

ans = 0
now_s_ind = 0
for i in range(len_t):
    now_t = t[i]
    if len(s_alpha_ind[now_t]) == 0:
        ans = -1
        break
    else:
        
        
        

        
        
        Inds = s_alpha_ind[now_t]
        ind = bisect.bisect_right(Inds, now_s_ind)
        
        
        

        if ind == len(Inds):
            ans += (len_s - now_s_ind + Inds[0])
            if i == 0:
                ans -= len_s
            now_s_ind = Inds[0]
        else:
            ans += Inds[ind] - now_s_ind
            now_s_ind = Inds[ind]
        


print(ans)

Solution (Python):
import bisect
s = input()
t = input()
n = len(s)
m = len(t)
indices = [[] for _ in range(26)]
for i in range(n):
    indices[ord(s[i]) - ord('a')].append(i)
for i in range(n):
    indices[ord(s[i]) - ord('a')].append(i + n)

ans = 0
p = 0
for i in range(m):
    c = ord(t[i]) - ord('a')
    if len(indices[c]) == 0:
        print(-1)
        exit()
    p = indices[c][bisect.bisect_left(indices[c], p)] + 1
    if p >= n:
        p -= n
        ans += n
ans += p
print(ans)

Solution (Python):
from bisect import bisect_right, bisect_left
s = [ord(i) - ord("a") for i in input()]
t = [ord(i) - ord("a") for i in input()]
index = [[] for _ in range(26)]

for i, x in enumerate(s):
    index[x].append(i)


l_s = len(s)

for x in index:
    if x:
        x.append(x[0] + l_s)

cnt = -1
for r in t:
    seq = index[r]
    if not seq:
        cnt = -2
        break
    i = cnt % l_s
    j = bisect_right(seq, i)
    cnt += seq[j] - i

print(cnt+1)

Solution (Python):
from bisect import bisect_right, bisect_left
s = [ord(i) - ord("a") for i in input()]
t = [ord(i) - ord("a") for i in input()]
index = [[] for _ in range(26)]

for i, x in enumerate(s):
    index[x].append(i)


l_s = len(s)

for x in index:
    if x:
        x.append(x[0] + l_s)

cnt = -1
for r in t:
    seq = index[r]
    if not seq:
        cnt = -2
        break
    i = cnt % l_s
    j = bisect_right(seq, i)
    cnt += seq[j] - i

print(cnt+1)

Solution (Python):
import sys, re, os
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import permutations, combinations, product, accumulate
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from fractions import gcd
from bisect import bisect, bisect_left

def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def S_MAP(): return map(str, input().split())
def LIST(): return list(map(int, input().split()))
def S_LIST(): return list(map(str, input().split()))

sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7

s = input()
t = input()

loop = 0
index = -1



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

dic = defaultdict(list)
t_set = set(t)

for i, c in enumerate(s):
    dic[c].append(i)

for i in range(len(t)):
    
    
    idx = bisect_left(dic[t[i]], index)
    
    if idx < len(dic[t[i]]):
        
        index = dic[t[i]][idx] + 1
    elif idx >= len(dic[t[i]]):
        loop += 1
        index = -1 
        idx = bisect_left(dic[t[i]], index)
        index = dic[t[i]][idx] + 1
print(len(s) * loop + index)

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

s = input()
t = input()
idx = defaultdict(list)
for i in range(len(s)):
    idx[s[i]].append(i)
num = 0
prev = -1
for c in t:
    l = len(idx[c])
    if l == 0:
        print(-1)
        exit()
    j = bisect_right(idx[c], prev)
    if j == l:
        prev = idx[c][0]
        num += 1
    else:
        prev = idx[c][j]
print(len(s) * num + prev + 1)

Solution (Python):
def main():
    from bisect import bisect_right
    s=input()
    t=input()
    ls=len(s)
    lt=len(t)

    dic={i:[] for i in set(t)}
    for i in range(ls):
        st=s[i]
        if st in dic:
            dic[st].append(i)  

    cnt=0
    idx=-1
    for i in range(lt):
        st=t[i]
        if dic[st]==[]:
            print(-1)
            exit()

        tmp_idx=bisect_right(dic[st],idx)

        if tmp_idx==len(dic[st]):
            cnt+=1
            idx=dic[st][0]
        
        else:
            idx=dic[st][tmp_idx]
    
    print(cnt*ls+idx+1)  
 
if __name__=='__main__':
    main()

Solution (Python):
import sys

import bisect

def main():
    s = input()
    t = input()
    
    index = [[] for _ in range(26)]
    for x,st in enumerate(s):
        index[ord(st)-ord("a")].append(x)
    
    roop,now = 0,-1
    for st in t:
        num = ord(st)-ord("a")
        if index[num] == []:
            print(-1)
            exit()
        else:
            pos = bisect.bisect_right(index[num],now)
            if pos == len(index[num]):
                roop += 1
                now = index[num][0]
            else:
                now = index[num][pos]
                
    print(roop*len(s)+now+1)
    
if __name__ == "__main__":
    main()

Solution (Python):
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians, atan, degrees
from itertools import permutations, combinations, product, accumulate
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from fractions import gcd
from bisect import bisect, bisect_left
import heapq
import numpy as np

def input(): return sys.stdin.readline().strip()
def INt(): return int(input())
def MAP(): return map(int, input().split())
def LISt(): return list(map(int, input().split()))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7

def main():
	s = input()
	t = input()
	
	if not set(s) >= set(t):
		print(-1)
		exit()

	dic = defaultdict(list)
	for i, char in enumerate(s):  
		dic[char].append(i)
	
	loop = 0
	index = -1
	for i in range(len(t)):
		idx = bisect_left(dic[t[i]], index)  
		if idx != len(dic[t[i]]):
			index = dic[t[i]][idx] + 1
		else:  
			loop += 1
			index = -1
			idx = bisect_left(dic[t[i]], index)
			index = dic[t[i]][idx] + 1

	print(len(s)*loop+index)

if __name__ == '__main__':
	main()

Solution (Python):
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians, atan, degrees
from itertools import permutations, combinations, product, accumulate
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from fractions import gcd
from bisect import bisect, bisect_left
import heapq
import numpy as np

def input(): return sys.stdin.readline().strip()
def INt(): return int(input())
def MAP(): return map(int, input().split())
def LISt(): return list(map(int, input().split()))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7

def main():
	s = input()
	t = input()
	if len(set(s)&set(t)) != len(set(t)):
		print(-1)
		exit()

	dic = defaultdict(list)
	for i, char in enumerate(s):  
		dic[char].append(i)
	
	loop = 0
	index = -1
	for i in range(len(t)):
		idx = bisect_left(dic[t[i]], index)  
		if idx != len(dic[t[i]]):
			index = dic[t[i]][idx] + 1
		else:  
			loop += 1
			index = -1
			idx = bisect_left(dic[t[i]], index)
			index = dic[t[i]][idx] + 1

	print(len(s)*loop+index)

if __name__ == '__main__':
	main()

Solution (Python):
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians, atan, degrees
from itertools import permutations, combinations, product, accumulate
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from fractions import gcd
from bisect import bisect, bisect_left
import heapq
import numpy as np

def input(): return sys.stdin.readline().strip()
def INt(): return int(input())
def MAP(): return map(int, input().split())
def LISt(): return list(map(int, input().split()))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7

def main():
	s = input()
	t = input()
	if len(set(s)&set(t)) != len(set(t)):
		print(-1)
		exit()

	dic = defaultdict(list)
	for i, char in enumerate(s):  
		dic[char].append(i)
	
	loop = 0
	index = -1
	for i in range(len(t)):
		if len(dic[t[i]]) == 0:
			print(-1)
			exit()
		idx = bisect_left(dic[t[i]], index)  
		if idx != len(dic[t[i]]):
			index = dic[t[i]][idx] + 1
		else:  
			loop += 1
			index = -1
			idx = bisect_left(dic[t[i]], index)
			index = dic[t[i]][idx] + 1

	print(len(s)*loop+index)

if __name__ == '__main__':
	main()

Solution (Python):
from bisect import bisect_left
from collections import defaultdict
d = defaultdict(list)

S = input()
T = input()


for i in range(len(S)):
    d[S[i]].append(i)


NoFind = False

sequence = 1  
index = -1
for i in range(len(T)):
    if len(d[T[i]]) == 0:
        NoFind = True
        break
    find = bisect_left(d[T[i]], index)
    if find != len(d[T[i]]):
        index = d[T[i]][find] + 1
    else:  
        sequence += 1
        index = -1
        find = bisect_left(d[T[i]], index)
        index = d[T[i]][find] + 1 
            
if NoFind:
    print(-1)
else:
    print(len(S)*(sequence-1) + index)

Solution (Python):
import bisect
s = input()
t = input()
data = {}
max_s = len(s) + 1
for i in range(26):
    data[chr(i + ord('a'))] = []
for i in range(len(s)):
    data[s[i]].append(i+1)
for i in range(26):
    data[chr(i + ord('a'))].append(max_s)
pre = 0
ans = 0
for i in range(len(t)):
    char = t[i]
    if len(data[char]) == 1:
        print(-1)
        exit()
    else:
        index = bisect.bisect_left(data[char], pre+1)
        if data[char][index] == max_s:
            ans += len(s) - pre
            pre = data[char][0]
            ans += pre
        else:
            ans += data[char][index] - pre
            pre = data[char][index]
print(ans)

Solution (Python):
al = "abcdefghijklmnopqrstuvwxyz"
d = {}
dn = {}
for a in al:
    d[a] = []
    dn[a] = 0
s = input()
for i in range(len(s)):
    d[s[i]].append(i)
    dn[s[i]] += 1

t = input()
import bisect
ans = 0
n = -1
for a in t:
    l = d[a]
    if l:
        res = bisect.bisect(l, n)
        if res == dn[a]:
            ans += 1
            n = l[0]
        else:
            n = l[res]
    else:
        ans = 0
        n = -2
        break
print(ans * len(s) + n + 1)

Solution (Python):
INF=float("inf")
def c2i(c): return ord(c)-ord("a")

def main():
    S=list(map(c2i, input()))
    N=len(S)
    T=list(map(c2i, input()))
    S*=2
    Next=[[INF]*26 for _ in range(N*2)]
    for i in range(N*2-2,-1,-1):
        for j in range(26):
            Next[i][j] = 1 if S[i%N]==j else Next[i+1][j]+1
    ans=0
    i=0
    for t in T:
        x=Next[i][t]
        if x==INF:
            print(-1)
            exit()
        i+=x
        i%=N
        ans+=x
    print(ans)


if __name__ == "__main__":
    main()

Solution (Python):
alphabetlist=['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']
S=input()
T=input()
Sdata=[[] for i in range(26)]
for i in range(0,len(S)):
    Sdata[alphabetlist.index(S[i])].append(i)
ans=0
for i in range(len(T)):
    if Sdata[alphabetlist.index(T[i])]==[]:
        ans=-1
if ans!=-1:
    sequence=0
    number=-1
    for i in range(0,len(T)):
        x=T[i]
        n=alphabetlist.index(x)
        start=0
        end=len(Sdata[n])-1
        while end-start>1:
            test=(end+start)//2
            if Sdata[n][test]>number:
                end=test
            else:
                start=test
        if Sdata[n][start]>number:
            number=Sdata[n][start]
        elif Sdata[n][end]>number:
            number=Sdata[n][end]
        else:
            sequence+=1
            number=Sdata[n][0]
    ans=sequence*len(S)+number+1
print(ans)

Solution (Python):
import bisect
s = input()
l = len(s)
ch = [[] for _ in range(26)]
s *= 2
for i in range(l*2):
  ch[ord(s[i]) - ord("a")].append(i)
  
t = input()
ans = 0
now = -1
for i in t:
  idx = ord(i) - ord("a")
  if not ch[idx]:
    print(-1)
    break
  temp = bisect.bisect_right(ch[idx], now)
  ans += ch[idx][temp] - now
  now = ch[idx][temp]%l
else:
  print(ans)

Solution (Python):
from itertools import *
from collections import *
from bisect import *
s=list(input())
t=input()
sets=set(s)
"""
a=len(s)*len(t)
maxcount=len(s)
for i in range(100):
    if maxcount<a:
        maxcount**=10
    else:
        break
"""

for T in t:
    if not T in sets:
        print(-1)
        exit()
N=len(s)
dic={}
for i in range(N):
    if not s[i] in dic:
        dic.update({s[i]:[i]})
    else:
        dic[s[i]].append(i)

count=0
prei=0
for i in range(len(t)):
    idx=bisect_left(dic[t[i]],prei)
    if idx<len(dic[t[i]]):
        prei=dic[t[i]][idx]+1
    else:
        prei=dic[t[i]][0]+1
        count+=N
    if i==len(t)-1:
        count+=prei



print(count)

Solution (Python):
from itertools import *
from collections import *
from bisect import *
s=list(input())
t=input()
sets=set(s)
"""
a=len(s)*len(t)
maxcount=len(s)
for i in range(100):
    if maxcount<a:
        maxcount**=10
    else:
        break
"""

for T in t:
    if not T in sets:
        print(-1)
        exit()
N=len(s)
dic={}
for i in range(N):
    if not s[i] in dic:
        dic.update({s[i]:[i]})
    else:
        dic[s[i]].append(i)

count=0
prei=0
for i in range(len(t)):
    idx=bisect_left(dic[t[i]],prei)
    if idx<len(dic[t[i]]):
        prei=dic[t[i]][idx]+1
    else:
        prei=dic[t[i]][0]+1
        count+=N
    if i==len(t)-1:
        count+=prei



if count<=len(s)*(10**100):
    print(count)
else:
    print(-1)

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

s, t = sys.stdin.read().split()
l = len(s)
s *= 2

def main():
    for c in t:
        try:
            s.index(c)
        except:
            return -1
    
    d = defaultdict(list)
    for i in range(l*2):
        d[s[i]].append(i)
    
    for c in d:
        d[c].sort()
    
    j = 0
    cnt = 0
    for c in t:
        k = bi_l(d[c], j)
        j = d[c][k]
        if j >= l:
            j -= l
            cnt += 1
        j += 1
    ans = l * cnt + j

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