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 sys
import math
import bisect
sys.setrecursionlimit(1000000000)
from heapq import heappush, heappop,heappushpop
from collections import defaultdict
from itertools import accumulate
from collections import Counter
from collections import deque
from operator import itemgetter
from itertools import permutations
mod = 10**9 + 7
inf = float('inf')
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))

s = input()
t = input()
n = len(s)
m = len(t)
f = [False]*26
f2 = [False]*26
alpha = 'abcdefghijklmnopqrstuvwxyz'
for i in range(n):
    f[alpha.index(s[i])] = True
for i in range(m):
    f2[alpha.index(t[i])] = True
for i in range(26):
    if not f[i] and f2[i]:
        print(-1)
        quit()
ans = 0
inde = s.index(t[0])
ans += inde+1
for i in range(1,m):
    s = s[inde+1:] + s[:inde+1]
    inde = s.index(t[i])
    ans += inde+1
print(ans)

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

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

ans = 0
x = -1
for i in range(len(t)):
    if t[i] not in ds:
        ans = -1
        break

    x_next = ds[t[i]][bisect_right(ds[t[i]], x)]
    ans += x_next - x
    x = x_next % n
    

print(ans)

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

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


    str_dict = defaultdict(list)



    for char in set(t):
        c_iter = finditer(char, s)
        flag = True
        for j in c_iter:
            flag = False
            str_dict[char] += [j.start() + 1]
        if flag:
            return '-1'


    ans = 0
    for i in t:
        remain = ans % len(s)
        array = str_dict[i]
        str_ind = bisect_right(array, remain)
        if str_ind != len(array):
            ans += array[str_ind] - remain
        else:
            ans += len(s) - remain + array[0]
    return ans


print(main())

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

ds = defaultdict(int)
for i in range(len(s)):
    ds[s[i]] += 1
dt = defaultdict(int)
for i in range(len(t)):
    dt[t[i]] += 1

possible = True
for ti in dt:
    if ti not in ds:
        possible = False
        break


if possible:
    n = len(s)
    pos = defaultdict(list)
    for i in range(n*2):
        pos[s[i%n]].append(i)

    edge = defaultdict(list)
    for c in pos:
        x = 0
        for i in range(n):
            if i >= pos[c][x]:
                x += 1
            edge[c].append(pos[c][x])

    
    
    ans = 0
    x = 0
    for i in range(n):
        if s[i] == t[0]:
            ans = i + 1
            x = i
            break

    
    for i in range(1, len(t)):
        ans += edge[t[i]][x%n] - x
        x = edge[t[i]][x%n] % n
        

else:
    ans = -1

print(ans)

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

p = 0
roop = 0
dic = [['' for i in range(len(s))] for j in range(26)]

for i in range(len(t)):
    dis = 0
    if dic[ord(t[i])-97][p] == '':
        for j in range(p,len(s)):
            if t[i] == s[j]:
                for k in range(p,j+1):
                    dic[ord(t[i])-97][k] = j
                dis = 1
                break
        if dis == 0:
            for j in range(0,p):
                if t[i] == s[j]:
                    for k in range(p,len(s)):
                        dic[ord(t[i])-97][k] = j
                    for k in range(0,j+1):
                        dic[ord(t[i])-97][k] = j
                    dis = 1
                    break
        if dis == 0:
            dis = 2
            break
    if p > dic[ord(t[i])-97][p]:
        roop += 1
    if dic[ord(t[i])-97][p] == len(s)-1:
        roop += 1        
        p = 0
    else:
        p = dic[ord(t[i])-97][p] + 1

if dis == 2:
    print(-1)
else:
    print(roop*len(s)+p)

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

d=defaultdict(list)

ls=len(s)
lt=len(t)

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

buf=-1
l=0
for i in range(lt):
    if not d[t[i]]:
        print(-1)
        sys.exit()
    idx=bisect.bisect_right(d[t[i]],buf)
    if idx>=len(d[t[i]]):
        buf=d[t[i]][0]
        l+=1
    else:
        buf=d[t[i]][idx]
print(l*ls+buf+1)

Solution (Python):
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10 ** 7)

from collections import defaultdict
from bisect import bisect_left

S = input().rstrip()
T = input().rstrip()

LS = len(S)

index = defaultdict(list)

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

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

print(x + 1)

Solution (Python):
from bisect import bisect
S=input()
T=input()
c=[[] for _ in range(26)]
for i,s in enumerate(S):
    j=ord(s)-ord("a")
    c[j].append(i)
for t in set(T):
    if not c[ord(t)-ord("a")]:
        print(-1)
        exit()
rnd=0
k=-1
for t in T:
    ti=ord(t)-ord("a")
    i=bisect(c[ti],k)
    if i==len(c[ti]):
        k=c[ti][0]
        rnd+=1
    else:
        k=c[ti][i]
        
print(rnd*len(S)+k+1)

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

for i in range(len(t)):
  if not t[i] in s:
    print(-1)
    break
else:
  j = -1
  counter = 0
  for i in range(len(t)):
    if t[i] in s[j+1:]:
      j = s[j+1:].find(t[i]) + j + 1
    else:
      counter += 1
      j = s.find(t[i])
  print(counter * len(s) + j + 1)

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


idx = -1
count = 0
if set(t) <= set(s):
    for i in t:
        idx = s.find(i,idx + 1)
        if idx == -1:
            idx = s.find(i)
            count += 1
        rep = count * len(s)
    print(idx+1+rep)
else:
    print(-1)

Solution (Python):
import bisect

s=input()
t=input()





char_appear = {ch: [] for ch in 'abcdefghijklmnopqrstuvwxyz'}
for i, ch in enumerate(s):
    char_appear[ch].append(i)

      
b=0
loop=0
condition=0

for j in range(len(t)):
  if len(char_appear[t[j]])<1:
    print(-1)
    condition=1
    break
  c=bisect.bisect(char_appear[t[j]],b)
 
  if j<1:
    b=char_appear[t[0]][0]    
  elif c == len(char_appear[t[j]]): 
     loop +=1
     b=char_appear[t[j]][0]
     if loop==10**100:
        print(-1)
        condition=1
        break
  else:
     b=char_appear[t[j]][c]
     


if condition==0:
 print(b+loop*len(s)+1)

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 bisect import bisect_right

s = ns()
t = ns()


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

if not ok:
    print(-1)
else:
    n = len(s)
    nex = [[] for _ in range(26)]
    sdouble = s + s
    orda = ord("a")
    for i, si in enumerate(sdouble):
        nex[ord(si) - orda].append(i)

    bef = t[:1]
    cur = s.index(t[:1])
    ans = cur

    for ti in t[1:]:
        chridx = ord(ti) - orda
        dest = bisect_right(nex[chridx], cur)
        ans += (nex[chridx][dest] - cur)
        cur = ans % n

    print(ans+1)

Solution (Python):


from collections import defaultdict
from bisect import bisect_right


def solve():
  
  S = str(input())
  T = str(input())

  
  Sdict = defaultdict(lambda:list())
  for i,c in enumerate(S):
    Sdict[c].append(i+1)

  idx = 0
  Tidx = [0 for _ in range(len(T)+1)]
  for i,c in enumerate(T):
    if len(Sdict[c]) == 0:
      return -1
    else:
      pos = bisect_right(Sdict[c],idx)
      if pos < len(Sdict[c]):
        Tidx[i+1] = Sdict[c][pos]
      else:
        Tidx[i+1] = Sdict[c][0]
      idx = Tidx[i+1]

  ans = 0
  for i in range(1,len(Tidx)):
    if Tidx[i-1] < Tidx[i]:
      ans += Tidx[i]-Tidx[i-1]
    else:
      ans += len(S)-Tidx[i-1]+Tidx[i]
  return ans


ans = solve()
print(ans)

Solution (Python):
from bisect import *
S = input()
T = input()
ds = {}
for i,s in enumerate(S) :
    if s not in ds :
        ds[s] = [i]
    else :
        ds[s].append(i)

ind = -1
cnt = 0

for t in T :
    if t not in ds :
        ans = -1
        break
else :
    for t in T :
        if ds[t][-1] <= ind :
            ind = ds[t][0]
            cnt += 1
        else :
            ind = ds[t][bisect_right(ds[t], ind)]
    ans = cnt * len(S) + ind + 1
print(ans)

Solution (Python):
import sys
from bisect import bisect_right as bisect
def main():
    input = sys.stdin.readline
    s = input()[:-1]
    t = input()[:-1]

    A = [[] for k in range(26)]
    for k in range(len(s)):
        A[ord(s[k])-97] += [k+1]
    ans = 0
    now = 0
    for k in range(len(t)):
        a = ord(t[k]) - 97
        if len(A[a]) == 0:
            print(-1)
            exit(0)
        if A[a][-1] <= now:
            ans += len(s)
            now = A[a][0]
        else:
            now = A[a][bisect(A[a],now)]
    print(ans+now)

if __name__ == '__main__':
    main()

Solution (Python):
s = input()
t = input()
 
idx = -1
count = 0
if set(t) <= set(s):
    for i in t:
        idx = s.find(i, idx+1)
        if idx == -1:
            idx = s.find(i)
            count += 1
    pdc = count * len(s)
    print((idx + 1) + pdc)
else:
    print(-1)

Solution (Python):
def e_strings_of_inpurity():
    from bisect import bisect
    S = input()
    T = input()

    char_appear = {ch: [] for ch in 'abcdefghijklmnopqrstuvwxyz'}
    for i, ch in enumerate(S):
        char_appear[ch].append(i)

    
    p = -1  
    loop = 0
    for t in T:
        if not char_appear[t]:
            return -1  
        idx = bisect(char_appear[t], p)
        
        loop += 1 if idx == len(char_appear[t]) else 0
        p = char_appear[t][idx % len(char_appear[t])]
    return loop * len(S) + p + 1

print(e_strings_of_inpurity())

Solution (Python):
def e_strings_of_inpurity():
    from bisect import bisect
    S = input()
    T = input()

    char_appear = {ch: [] for ch in 'abcdefghijklmnopqrstuvwxyz'}
    for i, ch in enumerate(S):
        char_appear[ch].append(i)

    
    p = -1  
    loop = 0
    for t in T:
        if not char_appear[t]:
            return -1  
        idx = bisect(char_appear[t], p)
        if idx == len(char_appear[t]):
            loop += 1  
            p = char_appear[t][0]
        else:
            p = char_appear[t][idx]
    return loop * len(S) + p + 1

print(e_strings_of_inpurity())

Solution (Python):
from bisect import bisect_left

ALPHABET = "abcdefghijklmnopqrstuvwxyz"


def main(s, t):
    positions = {char: [] for char in ALPHABET}
    for i, char in enumerate(s):
        positions[char].append(i)

    current = 0
    answer = 0
    for char in t:
        pos_num = len(positions[char])
        if pos_num < 1:
            return -1
        idx = bisect_left(positions[char], current)
        if idx < pos_num:
            current = positions[char][idx] + 1
        else:
            answer += len(s)
            idx = bisect_left(positions[char], 0)
            current = positions[char][idx] + 1

    answer += current
    return answer


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

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

idx = -1
count = 0
if set(t) <= set(s):
    for i in t:
        idx = s.find(i, idx+1)
        if idx == -1:
            idx = s.find(i)
            count += 1
    pdc = count * len(s)
    print((idx + 1) + pdc)
else:
    print(-1)

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

idx = -1
count = 0

if set(t) <= set(s):
    for i in t:
        idx = s.find(i, idx+1)
        if idx == -1:
            idx = s.find(i)
            count += 1
    pdc = count * len(s)
    total_idx = (idx + 1) + pdc 
    print(total_idx)
else:
    print(-1)

Solution (Python):
import bisect

NUM_LETTER = 26

def solve():
    s = list(raw_input())
    t = list(raw_input())
    Ns = len(s)
    
    charDict = [[] for i in range(NUM_LETTER)]
    for i in range(Ns):
        charDict[ord(s[i]) - ord('a')].append(i)
    
    
    ret = 0
    pk_1 = -1
    for i in range(len(t)):
        hashCharDict = ord(t[i]) - ord('a')
        
        if len(charDict[hashCharDict]) == 0:
            ret = -1
            break
        else:
            ind = bisect.bisect(charDict[hashCharDict], pk_1)
            if ind == len(charDict[hashCharDict]):
                ret += Ns - pk_1
                pk_1 = charDict[hashCharDict][0]
                ret += pk_1
            else:
                ret += charDict[hashCharDict][ind] - pk_1
                pk_1 = charDict[hashCharDict][ind]
        
    print ret

if __name__ == '__main__':
    solve()

Solution (Python):



def main():
    s = input().splitlines()[0]
    t = input().splitlines()[0]

    Slen = len(s)

    LookupTable = [[] for i in range(26)]
    for i, c in enumerate(s):
        v = ord(c) - ord('a')
        LookupTable[v].append(i)
    for i in range(26):
        LookupTable[i].append(-1)
        
    IndexTable = [0 for i in range(26)]
    NextTable = []
    for i, c in enumerate(s):
        v = ord(c) - ord('a')
        NextTable.append( [LookupTable[k][IndexTable[k]] for k in range(26)] )
        IndexTable[v] += 1
        if LookupTable[v][IndexTable[v]] < 0:
            IndexTable[v] = 0

    Index = 0
    Loop = 0
    for i, c in enumerate(t):
        v = ord(c) - ord('a')
        if NextTable[Index][v] < Index:
            Loop += 1
        Index = NextTable[Index][v]
        if Index < 0:
            print(-1)
            return
        Index += 1
        if Index >= Slen:
            Index = 0
            Loop += 1

    print(Loop*Slen+Index)


if __name__ == "__main__":
    main()

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

if not set(t) <= set(s):
  print(-1)
  exit()
  
result = 0
now_i = 0
for c in t:
  
  if not c in s[now_i:]: 
    result += len(s)-now_i
    now_i = 0
  di = s[now_i:].index(c)
  di += 1
  result += di
  now_i = (now_i + di) % len(s)
print(result)

Solution (Python):
import bisect

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

s=input()
ls=len(s)
t=input()
lt=len(t)
pos=[[] for _ in range(26)]
for i in range(ls):
  val=ctoi(s[i])
  pos[val].append(i)
larr=[0]*26
for i in range(26):
  larr[i]=len(pos[i])
pos2=[]
cnt=[0]*26
flag=True
num=-1
for i in range(lt):
  val=ctoi(t[i])
  if larr[val]==0:
    flag=False
    break
  tmp=bisect.bisect_right(pos[val],num)
  if tmp==larr[val]:
    num=pos[val][0]
  else:
    num=pos[val][tmp]
  pos2.append(num)
if flag==False:
  print(-1)
else:
  loop=0
  tmp=pos2[0]
  for i in range(1,lt):
    if pos2[i]<=tmp:
      loop+=1
    tmp=pos2[i]
  ans=loop*ls+(pos2[-1]+1)
  print(ans)

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

alphabet = 'abcdefghijklmnopqrstuvwxyz'
char = {c: [] for c in alphabet}
for i, c in enumerate(s):
    char[c].append(i)

if len(char[t[0]]) == 0:
    print(-1)
    exit()

result = char[t[0]][0]

for c in t[1:]:
    if len(char[c]) == 0:
        print(-1)
        exit()
    idx = bisect(char[c], result % len(s))
    result = result - result % len(s)
    try:
        result += char[c][idx]
    except IndexError:
        result += len(s) + char[c][0]

print(result+1)

Solution (Python):
import bisect

def main():
    s = input()
    t = input()
    sletters = [0]*26
    for i in range(len(s)):
        x = ord(s[i])-ord('a')
        if sletters[x] == 0:
            sletters[x] = [i]
        else:
            sletters[x].append(i)

    ans = 0
    curr_index = -1
    for i in t:
        x = ord(i)-ord('a')
        if sletters[x] == 0:
            print(-1)
            return
        index = bisect.bisect(sletters[x],curr_index)
        
        if index == len(sletters[x]):
            ans += len(s)-curr_index
            curr_index = sletters[x][0]
            ans += curr_index
        else:
            ans += sletters[x][index]-curr_index
            curr_index = sletters[x][index]
        

    print(ans)


main()

Solution (Python):



import sys
import math
import bisect
sys.setrecursionlimit(1000000000)
from heapq import heappush, heappop,heappushpop
from collections import defaultdict
from itertools import accumulate
from collections import Counter
from collections import deque
from operator import itemgetter
from itertools import permutations
mod = 10**9 + 7
inf = float('inf')
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))

s = input()
t = input()
n = len(s)
m = len(t)
f = [False]*26
f2 = [False]*26
alpha = 'abcdefghijklmnopqrstuvwxyz'
for i in range(n):
    f[alpha.index(s[i])] = True
for i in range(m):
    f2[alpha.index(t[i])] = True
for i in range(26):
    if not f[i] and f2[i]:
        print(-1)
        quit()
ans = 0
pre = s.index(t[0])
ans += pre+1
for i in range(1,m):
    s = s[pre+1:] + s[:pre+1]
    inde = s.index(t[i])
    ans += inde+1
    pre = inde
print(ans)

Solution (Python):
s = input()
t = input()
c = [[] for _ in range(26)]
total = 0
for i in range(len(s)):
    c[ord(s[i])-ord('a')].append(i)
idex = 0
run = -1
while(idex<len(t)):
    need = ord(t[idex])-ord('a')
    if len(c[need])==0:
        print(-1)
        exit()
    else:
        l = 0
        r = len(c[need])-1
        while(l<r):
            next = (l+r)//2
            if (c[need][next]> run):
                r=next
            else:
                l=next+1
        if c[need][r]>run:
            total+= c[need][r]-run
            run = c[need][r]

        else:
            total+=len(s)-1-run
            total+=c[need][0]+1
            run=c[need][0]
    idex+=1
print(total)

Solution (Python):
from sys import stdin
import bisect

s = stdin.readline().rstrip()
t = stdin.readline().rstrip()

ss = s+s
alpos = []

for i in range(26):
    alpos.append([])

for i in range(len(ss)):
   alpos[ord(ss[i])-ord('a')].append(i)

pos = -1
mpos= -1
for i in range(len(t)):
    tn = ord(t[i])-ord('a')
    if ( len(alpos[tn]) == 0 ):
        pos = -2
        break
    bpos = bisect.bisect_left(alpos[tn], mpos+1)
    pos += alpos[tn][bpos]-mpos
    mpos = pos%len(s)

print(pos+1)

Solution (Python):
s = input()
ns = len(s)
x = {}
for i in range(len(s)):
    if s[i] in x:
        x[s[i]] += [i]
    else:
        x[s[i]] = [i]
t = input()
i = len(s)-1
count = 0
import bisect
for j in range(len(t)):
    if t[j] in x:
        ni = bisect.bisect_right(x[t[j]],i)
        if ni == len(x[t[j]]):
            i = x[t[j]][0]
            count += 1
        else:
            i = x[t[j]][ni]
    else:
        print(-1)
        exit()
    
print(len(s)*(count-1)+i+1)

Solution (Python):
S = [ord(s) - 97 for s in input()]
T = [ord(t) - 97 for t in input()]
SS = S + S
ls = len(S)

indexes = [[] for _ in range(26)]
for i, s in enumerate(SS):
    indexes[s].append(i)
m = [[-1] * 26 for _ in range(2 * ls)]
for s in range(26):
    inds = [0] + indexes[s]
    for r in range(1, len(inds)):
        for i in range(inds[r-1], inds[r]):
            m[i][s] = inds[r] - i

ans = 0
i = ls - 1
for t in T:
    cnt = m[i][t]
    if cnt == -1:
        print(-1)
        exit()
    ans += cnt
    i = (i + cnt) % ls
print(ans)

Solution (Python):
S = [ord(s) - 97 for s in input()]
T = [ord(t) - 97 for t in input()]
SS = S + S
ls = len(S)

indexes = [[] for _ in range(26)]
for i, s in enumerate(SS):
    indexes[s].append(i)
m = [[-1] * 26 for _ in range(2 * ls)]
for s in range(26):
    inds = [0] + indexes[s]
    for r in range(1, len(inds)):
        for i in range(inds[r-1], inds[r]):
            m[i][s] = inds[r] - i

ans = 0
i = ls - 1
for t in T:
    cnt = m[i][t]
    if cnt == -1:
        print(-1)
        exit()
    ans += cnt
    i = (i + cnt) % ls
print(ans)

Solution (Python):
s = input()
t = input()
t_long = len(t)
position = [0] * t_long
rep = 0

if set(t) <= set(s):
    position[0] = s.find(t[0])
    for i in range(1, t_long):
        if s.find(t[i], position[i - 1] + 1) > -1:
            position[i] = s.find(t[i], position[i - 1] + 1)
        else:
            position[i] = s.find(t[i])
    for k in range(t_long - 1):
        if position[k + 1] <= position[k]:
            rep += 1
    print(rep * len(s) + position[t_long - 1] + 1)
else:
    print(-1)

Solution (Python):
import collections, bisect
s = tuple(input())
t = tuple(input())
ls = len(s)
idx = collections.defaultdict(list)
dct = collections.defaultdict(list)
ln = -1
loop = 0
for i, v in enumerate(s):
    idx[v].append(i)
for i in t:
    t_idx = idx[i]
    if t_idx:
        bn = bisect.bisect_left(t_idx, ln + 1)
        if bn >= len(t_idx):
            ln = t_idx[0]
            loop += 1
        else:
            ln = t_idx[bn]
    else:
        print(-1)
        exit()
print(ls * loop + ln + 1)

Solution (Python):
s = input()
t = input()
max = 10**100
now = t[0]
cnt1 = 0
cnt2 = 0

while True:
	temp = s[:]
	if cnt2 == len(t):
		print(cnt1)
		break
	if max == 0:
		print("-1")
		break
	while True:
		num = temp.find(now)
		if num != -1:
			cnt2+=1
			cnt1+=num+1
			
			if cnt2 < len(t):
				now = t[cnt2]
			else:
				break
			temp = temp[num+1:]
			continue
		else:
			if temp == s:
				print("-1")
				exit(0)
			else:
				cnt1+=len(temp)
			break
	max-=1

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

Spos = [[] for _ in range(26) ]
ord_a = ord('a')
for i in range(len(S)):
    Spos[ord(S[i])-ord_a].append(i)

for t in set(T):
    if len(Spos[ord(t)-ord_a]) == 0:
        print(-1)
        exit()

copy = 0
pos = -1
for t in T:
    array = Spos[ord(t)-ord_a]
    p = bisect.bisect_right(array, pos)
    if p == len(array):
        copy += 1
        pos = array[0]
    else:
        pos = array[p]

ans = copy * len(S) + (pos + 1)
print(ans)

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

S = input()
dS = defaultdict(list)
T = input()
for i in range(len(S)):
    dS[S[i]].append(i+1)
if not dS[T[0]]:
    print(-1)
    exit()
now = min(dS[T[0]])
ans = now
for i in range(1, len(T)):
    t = T[i]
    if not dS[t]:
        print(-1)
        exit()
    b = bisect_right(dS[t], now)
    if b == len(dS[t]):
        ans += len(S) - now
        now = min(dS[t])
        ans += now
    else:
        ans += dS[t][b] - now
        now = dS[t][b]
print(ans)

Solution (Python):
import collections
import bisect

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

    ns, nt = len(s), len(t)
    cs, ct = set(list(s)), set(list(t))
    for c in ct:
        if c not in cs: return -1

    
    
    
    
    
    
    

    d = collections.defaultdict(list)
    for i in range(ns):
        if s[i] in ct: d[s[i]].append(i)
    
    i = 0
    for c in t:
        
        j = i % ns
        k = bisect.bisect_left(d[c], j)
        if k == len(d[c]):
            i = (i // ns + 1)*ns + d[c][0]
        else:
            if j <= d[c][k]:
                i = (i // ns)*ns + d[c][k]
            else:
                i = (i // ns + 1)*ns + d[c][k]
        
        i += 1
    return i
    


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

Solution (Python):
from bisect import bisect_left
import sys

input = sys.stdin.readline

s = input().strip()
n = len(s)
t = input().strip()

d = [[] for _ in range(26)]
base = ord('a')
for i, c in enumerate(s):
    idx = ord(c) - base
    d[idx].append(i)

string_count = 0
cur = -1
for tt in t:
    cur += 1
    idx = ord(tt) - base
    pos_lst = d[idx]
    lst_len = len(pos_lst)

    if not lst_len:
        print(-1)
        exit()
    pos = bisect_left(pos_lst, cur)  
    if lst_len == pos:
        string_count += 1
        cur = pos_lst[0]
    else:
        cur = pos_lst[pos]

    

print(string_count * n + cur + 1)

Solution (Python):
import bisect
import sys

s = input()
t = input()
ss = s + s
n = len(s)

az_pos = [[] for i in range(ord("z") - ord("a") + 1)]
for i, si in enumerate(s):
    az_pos[ord(si) - ord("a")].append(i)

ans = 0

past = 0
for ti in t:
    char = ord(ti) - ord("a")
    if len(az_pos[char]) == 0:
        print(-1)
        sys.exit()

    r = bisect.bisect_left(az_pos[char], past)
    if r >= len(az_pos[char]):
        ans += n
        r = bisect.bisect_left(az_pos[char], 0)
    past = az_pos[char][r] + 1

print(ans + past)

Solution (Python):
from bisect import bisect_left
a=input()
b=input()
c=[[]for i in range(26)]
for i in range(len(a)):
  c[ord(a[i])-97].append(i)

m=-1
ans=0
roop=0
for i in range(len(b)):
  s=ord(b[i])-97
  if c[s]==[]:
    print(-1)
    exit()
  else:
    p=bisect_left(c[s],m+1)
    if p<len(c[s]):
      m=c[s][p]
    else:
      roop+=1
      m=c[s][0]
print(roop*len(a)+m+1)

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 as bs
from collections import defaultdict


def main():
    S = input()
    T = input()
    
    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 sys
input = sys.stdin.readline

from bisect import bisect_left as bs
from collections import defaultdict


def main():
    S = input().rstrip()
    T = input().rstrip()
    
    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 bisect

s = input()
t = input()

s_dict = {}
for i, si in enumerate(s):
    if si not in s_dict:
        s_dict[si] = [i]
    else:
        s_dict[si].append(i)



s_len = len(s)
counter = 0
fail = False
for ti in t:
    if ti not in s_dict:
        fail = True
        break
    
    c_in_s = counter % s_len
    c = bisect.bisect_left(s_dict[ti], c_in_s)
    if c == len(s_dict[ti]):
        counter += s_len - c_in_s
        counter += s_dict[ti][0]
        counter += 1
    else:
        counter += s_dict[ti][c] - c_in_s
        counter += 1

print(counter if not fail else '-1')

Solution (Python):
import sys,collections as cl,bisect as bs
sys.setrecursionlimit(100000)
mod = 10**9+7
Max = sys.maxsize
def l(): 
    return list(map(int,input().split()))
def m(): 
    return map(int,input().split())
def onem(): 
    return int(input())
def s(x): 
    a = []
    aa = x[0]
    su = 1
    for i in range(len(x)-1):
        if aa != x[i+1]:
            a.append([aa,su])
            aa = x[i+1]
            su = 1
        else:
            su += 1
    a.append([aa,su])
    return a
def jo(x): 
    return " ".join(map(str,x))
def max2(x): 
    return max(map(max,x))
import fractions
from functools import reduce
def gcd(*numbers):
    return reduce(fractions.gcd, numbers)

def gcd_list(numbers):
    return reduce(fractions.gcd, numbers)
def lcm_base(x, y):
    return (x * y) // fractions.gcd(x, y)

def lcm(*numbers):
    return reduce(lcm_base, numbers, 1)

def lcm_list(numbers):
    return reduce(lcm_base, numbers, 1)


s = list(input())

t = list(input())
flag = -1
on = [[-1 for j in range(len(s))] for i in range(26)]

al = [-1 for i in range(26)]
alll = [0 for i in range(26)]
for i in range(len(s)):
    k = ord(s[i]) - 97
    on[k][i] = i
    if al[k] == -1:
        al[k] = i

for i in range(26):
    for j in range(len(s)-2,-1,-1):
        if on[i][j+1] != -1 and on[i][j] == -1:
            on[i][j] = on[i][j+1]
co = 0
ppp = 0
t = cl.deque(t)
while t:
    k = t.popleft()
    kkk = al[ord(k)-97]
    ppp = kkk+1
    if kkk == -1:
        print(kkk)
        exit()
    while t:
        kt = t.popleft()
        if k == kt:
            if kkk == len(s)-1:
                t.appendleft(kt)
                break
            else:
                kk = on[ord(kt)-97][kkk+1] 
                if kkk >= kk:
                    t.appendleft(kt)
                    break
                else:
                    ppp = kk+1
                    kkk = kk
                    k = kt
        else:
            kk = on[ord(kt)-97][kkk]
            if kkk >= kk:
                t.appendleft(kt)
                break
            else:
                ppp = kk+1
                kkk = kk
                k = kt
    if len(t) != 0:
        co += 1

print(len(s)*co + ppp)

Solution (Python):
import bisect

s = input()
t = input()

lst = [[] for _ in range(30)]
ch = 'abcdefghijklmnopqrstuvwxyz'
for k, i in enumerate(s+s):
    lst[ch.find(i)].append(k)

len_s = len(s)

count = 0
index = -1
for i in t:
    if lst[ch.find(i)] == []:
        print(-1)
        break
    next_index = lst[ch.find(i)][bisect.bisect_right(lst[ch.find(i)], index)]
    count += next_index - index
    if next_index >= len_s:
        next_index -= len_s
    index = next_index
else:
    print(count)