Problem:


Score : 500 points

Problem Statement

You are given a string S of length N consisting of lowercase English letters.

Process Q queries of the following two types:

Type 1: change the i_q-th character of S to c_q. (Do nothing if the i_q-th character is already c_q.)

Type 2: answer the number of different characters occurring in the substring of S between the l_q-th and r_q-th characters (inclusive).

Constraints

N, Q, i_q, l_q, and r_q are integers.

S is a string consisting of lowercase English letters.

c_q is a lowercase English letter.

1 \leq N \leq 500000

1 \leq Q \leq 20000

|S| = N

1 \leq i_q \leq N

1 \leq l_q \leq r_q \leq N

There is at least one query of type 2 in each testcase.

Input

Input is given from Standard Input in the following format:

N
S
Q
Query_1
\vdots
Query_Q

Here, Query_i in the 4-th through (Q+3)-th lines is one of the following:

1 i_q c_q

2 l_q r_q

Output

For each query of type 2, print a line containing the answer.

Sample Input 1

7
abcdbbd
6
2 3 6
1 5 z
2 1 1
1 4 a
1 7 d
2 1 7

Sample Output 1

3
1
5

In the first query, cdbb contains three kinds of letters: b , c , and d, so we print 3.

In the second query, S is modified to abcdzbd.

In the third query, a contains one kind of letter: a, so we print 1.

In the fourth query, S is modified to abcazbd.

In the fifth query, S does not change and is still abcazbd.

In the sixth query, abcazbd contains five kinds of letters: a, b, c, d, and z, so we print 5.



Sample input:
7
abcdbbd
6
2 3 6
1 5 z
2 1 1
1 4 a
1 7 d
2 1 7


Sample output:
3
1
5

Submission status: Runtime Error

Solution code:
#!/usr/bin/env python3

import sys
import math
from bisect import bisect_right as br
from bisect import bisect_left as bl
sys.setrecursionlimit(2147483647)
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
from sortedcontainers import SortedList
mod = 10**9 + 7
inf = float('inf')
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))

tmp = 'abcdefghijklmnopqrstuvwxyz'
n = I()
s = list(input())
cnt = [0]*n
alpha = defaultdict(list)
for i in range(n):
    alpha[s[i]].append(i)

q = I()
f = defaultdict(list)
for _ in range(q):
    num, i, c = input().split()
    i = int(i) - 1
    if int(num) == 1:
        if s[int(i)-1] == c:
            continue
        r = br(f[s[i]],i)
        f[s[i]] = f[s[i]][:r] + [i] + f[s[i]][r:]
        r = br(alpha[c],i)
        alpha[c] = alpha[c][:r] + [i] + alpha[c][r:]
        s[i] = c
    else:
        cnt = 0
        c = int(c)-1
        for j in range(26):
            l = bl(alpha[tmp[j]],i)
            r = br(alpha[tmp[j]],c)
            L = bl(f[tmp[j]],i)
            R = br(f[tmp[j]],c)
            if r - l - (R - L) > 0:
                cnt += 1
        print(cnt)

Submission status: Runtime Error

Solution code:
#!/usr/bin/env python3

import sys
import math
import bisect
from bisect import bisect_right as br
from bisect import bisect_left as bl
sys.setrecursionlimit(2147483647)
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
from sortedcontainers import SortedList
mod = 10**9 + 7
inf = float('inf')
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))

tmp = 'abcdefghijklmnopqrstuvwxyz'
n = I()
s = list(input())
cnt = [0]*n
alpha = defaultdict(list)
for i in range(n):
    alpha[s[i]].append(i)

q = I()
f = defaultdict(list)
for _ in range(q):
    num, i, c = input().split()
    i = int(i) - 1
    if int(num) == 1:
        if s[int(i)-1] == c:
            continue
        bisect.insort_right(f[s[i]],i)
        bisect.insort_right(alpha[c],i)
        s[i] = c
    else:
        cnt = 0
        c = int(c)-1
        for j in range(26):
            l = bl(alpha[tmp[j]],i)
            r = br(alpha[tmp[j]],c)
            L = bl(f[tmp[j]],i)
            R = br(f[tmp[j]],c)
            if r - l - (R - L) > 0:
                cnt += 1
        print(cnt)

Submission status: Runtime Error

Solution code:
class segtree:

    def __init__(self, n,operator,identity):
        nb = bin(n)[2:]
        bc = sum([int(digit) for digit in nb])
        if bc == 1:
            self.num_end_leaves = 2**(len(nb)-1)
        else:
            self.num_end_leaves = 2**(len(nb))

        self.array = [identity for i in range(self.num_end_leaves * 2)]
        self.identity = identity
        self.operator =operator

    def update(self,x,val):
        actual_x = x+self.num_end_leaves
        self.array[actual_x] = val
        while actual_x > 0 :
            actual_x = actual_x//2
            self.array[actual_x] = self.operator(self.array[actual_x*2],self.array[actual_x*2+1])

    def get(self,q_left,q_right,arr_ind=1,leaf_left=0,depth=0):
        width_of_floor = self.num_end_leaves//(2**depth)
        leaf_right = leaf_left+width_of_floor-1

        if leaf_left > q_right or leaf_right < q_left:
            return  self.identity

        elif leaf_left >= q_left and leaf_right <= q_right:
            return self.array[arr_ind]

        else:
            val_l = self.get(q_left,q_right,2*arr_ind,leaf_left,depth+1)
            val_r = self.get(q_left,q_right,2*arr_ind+1,leaf_left+width_of_floor//2,depth+1)
            return self.operator(val_l,val_r)


import sys
input = sys.stdin.readline
N=int(input())
S=[i for i in input()]
Q=int(input())

s_tree = segtree(N,(lambda x,y:set(x|y)),set()) 
for i in range(N):
    s_tree.update(i, set(S[i]))

for _ in range(Q):
    f, a b =(i for i in input().split())
    if int(f)==1:
        s_tree.update(int(a)-1,set(b))
    else:
        print(len(s_tree.get(int(a)-1, int(b)-1)))

Submission status: Runtime Error

Solution code:
#####segfunc######
def segfunc(x,y):
    if type(x) is int:
        return x+y
    res = len(set([x,y]))
    if x == None:
        res -= 1
    if y == None:
        res -= 1
    return res
def init(init_val):
    #set_val
    for i in range(len(init_val)):
        seg[i+num-1]=init_val[i]   
    #built
    for i in range(num-2,-1,-1) :
        seg[i]=segfunc(seg[2*i+1],seg[2*i+2]) 
    
def update(k,x):
    k += num-1
    seg[k] = x
    while k:
        k = (k-1)//2
        seg[k] = segfunc(seg[k*2+1],seg[k*2+2])
    
def query(p,q):
    if q<=p:
        return ide_ele
    p += num-1
    q += num-2
    res=ide_ele
    while q-p>1:
        if p&1 == 0:
            res = segfunc(res,seg[p])
        if q&1 == 1:
            res = segfunc(res,seg[q])
            q -= 1
        p = p//2
        q = (q-1)//2
    if p == q:
        res = segfunc(res,seg[p])
    else:
        res = segfunc(segfunc(res,seg[p]),seg[q])
    return res

#####単位元######
n = int(input())
s = list(input())
ide_ele = None
num =2**(n-1).bit_length()
seg=[ide_ele]*(2*num - 1)
init(s)
for i in range(int(input())):
    a,b,c = input().split()
    if a == "1":
        update(int(b) -1, c)
    else:
        if b == c:
            print(1)
        else:
            print(query(int(b)-1,int(c)-1))

Submission status: Runtime Error

Solution code:
class segtree:

    def __init__(self, n,operator,identity):
        nb = bin(n)[2:]
        bc = sum([int(digit) for digit in nb])
        if bc == 1:
            self.num_end_leaves = 2**(len(nb)-1)
        else:
            self.num_end_leaves = 2**(len(nb))

        self.array = [identity for i in range(self.num_end_leaves * 2)]
        self.identity = identity
        self.operator =operator

    def update(self,x,val):
        actual_x = x+self.num_end_leaves
        self.array[actual_x] = val
        while actual_x > 0 :
            actual_x = actual_x//2
            self.array[actual_x] = self.operator(self.array[actual_x*2],self.array[actual_x*2+1])

    def get(self,q_left,q_right,arr_ind=1,leaf_left=0,depth=0):
        width_of_floor = self.num_end_leaves//(2**depth)
        leaf_right = leaf_left+width_of_floor-1

        if leaf_left > q_right or leaf_right < q_left:
            return  self.identity

        elif leaf_left >= q_left and leaf_right <= q_right:
            return self.array[arr_ind]

        else:
            val_l = self.get(q_left,q_right,2*arr_ind,leaf_left,depth+1)
            val_r = self.get(q_left,q_right,2*arr_ind+1,leaf_left+width_of_floor//2,depth+1)
            return self.operator(val_l,val_r)


import sys
input = sys.stdin.readline
N=int(input())
S=[i for i in input()]
Q=int(input())

s_tree = segtree(N,(lambda x,y:set(x+y)),set()) 
for i in range(N):
    s_tree.update(i, set(S[i]))

for _ in range(Q):
    f, a, b =(i for i in input().split())
    if int(f)==1:
        s_tree.update(int(a)-1,set(b))
    else:
        print(len(s_tree.get(int(a)-1, int(b)-1)))

Submission status: Runtime Error

Solution code:
#!/usr/bin/env python3

import sys
import math
from bisect import bisect_right as br
from bisect import bisect_left as bl
sys.setrecursionlimit(2147483647)
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
from sortedcontainers import SortedList
mod = 10**9 + 7
inf = float('inf')
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))

tmp = 'abcdefghijklmnopqrstuvwxyz'
n = I()
s = list(input())
cnt = [0]*n
alpha = defaultdict(list)
for i in range(n):
    alpha[s[i]].append(i)

q = I()
f = defaultdict(list)
for _ in range(q):
    num, i, c = input().split()
    i = int(i) - 1
    if int(num) == 1:
        if s[int(i)-1] == c:
            continue
        f[s[i]] = SortedList(f[s[i]])
        f[s[i]].add(i)
        alpha[c] = SortedList(alpha[c])
        alpha[c].add(i)
        s[i] = c
    else:
        cnt = 0
        c = int(c)-1
        for j in range(26):
            l = bl(alpha[tmp[j]],i)
            r = br(alpha[tmp[j]],c)
            L = bl(f[tmp[j]],i)
            R = br(f[tmp[j]],c)
            if r - l - (R - L) > 0:
                cnt += 1
        print(cnt)

Submission status: Runtime Error

Solution code:
n=int(input())
s=list(input())

num=2**(n-1).bit_length()
st=[set() for _ in range(2*num)]

def update1(pos,x):
  pos+=num
  st[pos].add(x)
  while pos>=0:
    pos=(pos-1)//2
    st[pos]=st[2*pos+1]|st[2*pos+2]
    
def update2(pos,x):
  pos+=num
  st[pos].discard(x)
  while pos>=0:
    pos=(pos-1)//2
    st[pos]=st[2*pos+1]|st[2*pos+2]
    st[pos].discard(x)
    
def query(l,r):
  tl=l+num
  tr=r+num
  ret=set()
  while tl<tr:
    if tr&1==1:
      tr-=1
      ret=ret|st[tr-1]
    if tl&1==1:
      ret=ret|st[tl-1]
      tl+=1
    tl=tl//2
    tr=tr//2
  return len(ret)

for i in range(n):
  update1(i,s[i])

q=int(input())
for _ in range(q):
  a,b,c=map(str,input().split())
  a=int(a)
  b=int(b)
  if a==1:
    if c==s[b-1]:
      continue
    update2(b,s[b-1])
    s[b-1]=c
    update1(b,c)
  elif a==2:
    c=int(c)
    print(query(b,c+1))

Submission status: Runtime Error

Solution code:
n=int(input())
s=input()
q=int(input())

for i in range(q):
    type,iq,q=map(str,input().split())
'''
    if type == "1":
        s = "".join([s[:int(iq)-1],q,s[int(iq):]])
'''
    if type =="2":
        print(len(set(s[int(iq)-1:int(q)])))

Submission status: Runtime Error

Solution code:
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
import sys
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul, sub, or_

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

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


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


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


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


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


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


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



def mt(f):
    import time

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

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

    return wrap


class SegmentTree:
	def __init__(self, orig, func, unit):
		_len = len(orig)
		self.func = func
		self.size = 1 << (_len - 1).bit_length()
		self.tree = [unit] * self.size + orig + [unit] * (self.size - _len)
		self.unit = unit

		for i in range(self.size - 1, 0, -1):
			self.tree[i] = func(self.tree[i * 2], self.tree[i * 2 + 1])

	def update(self, i, v):
		i += self.size
		self.tree[i] = v
		while i:
			i //= 2
			self.tree[i] = self.func(self.tree[i * 2], self.tree[i * 2 + 1])

	def find(self, l, r):
		l += self.size
		r += self.size
		ret = self.unit
		while l < r:
			if l & 1:
				ret = self.func(ret, self.tree[l])
				l += 1
			if r & 1:
				r -= 1
				ret = self.func(ret, self.tree[r])
			l //= 2
			r //= 2
		return ret

@mt
def slv(N, S, Q):
    st = SegmentTree([1 << (ord(c) - ord('a')) for c in S] * N, or_, 0)

    for q in Q:
        if q[0] == '1':
            i = int(q[1]) - 1
            c = q[2]
            st.update(i, 1 << (ord(c) - ord('a')))
        if q[0] == '2':
            i = int(q[1]) - 1
            j = int(q[2]) - 1
            ans = 0
            v = st.find(i, j+1)
            for k in range(26):
                if (1 << k) & v:
                    ans += 1
            print(ans)
    # return ans


def main():
    N = read_int()
    S = read_str()
    Q = [read_str_n() for _ in range(read_int())]
    (slv(N, S, Q))

if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
import bisect

def sRaw():
    return input().rstrip("\r")


def iRaw():
    return int(input())


def ssRaw():
    return input().split()


def isRaw():
    return list(map(int, ssRaw()))


INF = 1 << 29

DIV = (10**9) + 7


def mod_inv_prime(a, mod=DIV):
    return pow(a, mod-2, mod)


def ncr(n, r, mod=DIV):
	r = min(r, n-r)
	ret = 1
	for i in range(1, r+1):
		ret = ret * (n-i+1) % mod
		ret = ret * mod_inv(i, mod) % mod
	return ret


def mod_inv(a, b):
    r = a
    w = b
    u = 1
    v = 0
    while w != 0:
        t = r//w
        r -= t*w
        r, w = w, r
        u -= t*v
        u, v = v, u
    return (u % b+b) % b


def CONV_TBL(max, mod=DIV):
    fac, finv, inv = [0]*max, [0]*max, [0]*max
    fac[0] = fac[1] = 1
    finv[0] = finv[1] = 1
    inv[1] = 1
    for i in range(2, max):
        fac[i] = fac[i-1]*i % mod
        inv[i] = mod - inv[mod % i] * (mod//i) % mod
        finv[i] = finv[i-1]*inv[i] % mod

    class CONV:
        def __init__(self):
            pass

        def ncr(self, n, k):
            if(n < k):
                return 0
            if(n < 0 or k < 0):
                return 0
            return fac[n]*(finv[k]*finv[n-k] % mod) % mod
    return CONV()


def main():
    N = iRaw()
    S = sRaw()
    Q = iRaw()
    Qs = [c for c in S]
    c_dict={}
    for c in range(ord('a'), ord('z')+1):
        c_dict[chr(c)] = []
    for idx,c in enumerate(Qs):
        c_dict[c].append(idx)
        
    for qidx in range(Q):
        query = ssRaw()
        if query[0]=="1":
            i = int(query[1])-1
            c = query[2]
            old_c = Qs[i]
            if c!= old_c:
                Qs[i]=c
                bi = bisect.bisect_left(c_dict[old_c],i)
                tmp = c_dict[S[i]]  # S[i]を更新しなきゃ
                del c_dict[S[i]][bisect.bisect_left(tmp, i)]
                # cのidxに挿入し直す
                bisect.insort_left(c_dict[c], bi)
        else:
            l = int(query[1])-1
            r = int(query[2])-1
            ret = 0
            for v in c_dict.values():
                l_idx = bisect.bisect_left(v, l)
                r_idx = bisect.bisect_right(v, r)
                if r_idx - l_idx > 0:
                    ret += 1
            print(ret)

    return -1


if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
import sys
# input = sys.stdin.buffer.readline
def getN():
    return int(input())
def getNM():
    return map(int, input().split())
def getlist():
    return list(map(int, input().split()))
import math
import heapq
import bisect
from collections import defaultdict, Counter, deque
MOD = 10**9 + 7
INF = 10**21


class Segtree_op():
    def __init__(self, n):
        self.size = 1
        while (n >= 1):
            self.size = self.size << 1
            n = n // 2

        self.arr = [self.unit() for i in range(self.size * 2)]

    def op(self, lch, rch):
        # sum
        return lch + rch

        # update min with holding index
        # if lch[0] <= rch[0]:
        #     return lch
        # else:
        #     return rch

    def unit(self):
        return 0

    def update(self, k, val):
        k += self.size - 1
        self.arr[k] = val
        while (k):
            k = (k - 1) // 2
            self.arr[k] = self.op(self.arr[k * 2 + 1], self.arr[k * 2 + 2])

    def query(self, l, r):
        L = l + self.size
        R = r + self.size
        s = self.unit()
        while L < R:
            if R & 1:
                R -= 1
                s = self.op(s, self.arr[R - 1])

            if L & 1:
                s = self.op(s, self.arr[L - 1])
                L += 1
            L >>= 1
            R >>= 1
        return s

    # def show(self):
    #     idx = 1
    #     while (idx <= self.size):
    #         print(self.arr[idx - 1:idx * 2 - 1])
    #         idx *= 2


def main():
    n = getN()
    s = input().strip()
    q = getN()

    # SegTreeをa-zぶん用意する 3文字目がbならsegs[b]の3番目にフラグ1が立つ
    segs = [Segtree_op(n) for i in range(26)]
    for i, c in enumerate(s):
        segs[ord(c) - ord("a")].update(i, 1)

    for query in range(q):
        operand, a, b = input().split()
        if operand == "1":
            # 0-indexed
            a = int(a) - 1
            segs[ord(s[a]) - ord("a")].update(a, 0)
            segs[ord(b) - ord("a")].update(a, 1)
            s[a] = b

        else:  # operand == "2"
            tmp = 0
            # 0-indexed
            a, b = int(a) - 1, int(b) - 1
            for se in segs:
                # a-zそれぞれのSegTreeについて、区間内にフラグが立っていれば tmp += 1
                # 文字自体ではなくその間にindexが降られているので、右側を+1
                if se.query(a, b+1) > 0:
                    tmp += 1
            print(tmp)

    # print(segs[0].arr)

if __name__ == '__main__':
    main()

"""
7 
aaaabbb
3
1 7 c
2 1 5
2 1 7
>> 2
>> 3


26 
abcdefghijklmnopqrstuvwxyz
7
2 1 26
2 2 26
2 5 5
2 11 20
2 25 26 
1 1 z
2 1 26
>> 26
>> 25
>> 1
>> 10
>> 2
>> 25
"""

Submission status: Runtime Error

Solution code:
import sys
N = int(input())
S =list(input())
Q = int(input())
T = []
while True:
    try:
        T.append(list(input().split()))
    except:
        break;

cnt = 0

def funk(x ,y):
    global S
    for s in range(x,y):
        S[int(T[s][1])-1] = T[s][2]    
    return S

for i in range(Q):
    if int(T[i][0]) == 2:
        funk(cnt,i)
        cnt = i+1
        print(S)
        print(len(set(S[int(T[i][1])-1:int(T[i][2])])))

Submission status: Runtime Error

Solution code:
N = int(input())
S = list(input())
Q = int(input())
query = [None]*N
for i in range(Q):
    query[i] = tuple(map(str, input().split()))

for i in range(Q):
    if query[i][0] == "1":
        S[int(query[i][1])-1] = query[i][2]
    else:
        start = int(query[i][1])-1
        end = int(query[i][2])
        ans = len(set( S[start:end]))
        print(ans)

Submission status: Runtime Error

Solution code:
#!/usr/bin/env python3
from collections import defaultdict,deque
from heapq import heappush, heappop
from bisect import bisect_left, bisect_right
import sys, random, itertools, math
sys.setrecursionlimit(10**5)
input = sys.stdin.readline
sqrt = math.sqrt
def LI(): return list(map(int, input().split()))
def LF(): return list(map(float, input().split()))
def LI_(): return list(map(lambda x: int(x)-1, input().split()))
def II(): return int(input())
def IF(): return float(input())
def LS(): return input().split()
def S(): return list(input().rstrip())
def IR(n): return [II() for _ in range(n)]
def LIR(n): return [LI() for _ in range(n)]
def FR(n): return [IF() for _ in range(n)]
def LFR(n): return [LI() for _ in range(n)]
def LIR_(n): return [LI_() for _ in range(n)]
def SR(n): return [S() for _ in range(n)]
def LSR(n): return [LS() for _ in range(n)]
mod = 1000000007
inf = float('INF')


class BinaryIndexedTree:
    # http://hos.ac/slides/20140319_bit.pdf
    def __init__(self, size):
        """
        :param int size:
        """
        self.bit = [0 for _ in range(size)]
        self.size = size

    def add(self, i, w):
        """
        i番目にwを加える
        :param int i:
        :param int w:
        :return:
        """
        x = i + 1
        while x <= self.size:
            self.bit[x - 1] += w
            x += x & -x
        return

    def sum(self, i):
        """
        [0,i]の合計
        :param int i:
        :return:
        """
        res = 0
        x = i + 1
        while x > 0:
            res += self.bit[x - 1]
            x -= x & -x
        return res

    def search(self, x):
        """
        二分探索。和がx以上となる最小のインデックス(>= 1)を返す
        :param int x:
        :return :
        """
        i = 1
        s = 0
        step = 1 << (self.size.bit_length() - 1)
        while step:
            if i + step <= self.size and s + self.bit[i + step - 1] < x:
                i += step
                s += self.bit[i - 1]
            step >>= 1
        return i

    def __len__(self):
        return self.size

#solve
def solve():
    n = II()
    s = S()
    q = II()
    ans = [BinaryIndexedTree(n + 1) for i in range(27)]
    lis = [ord(si) - ord("a") for si in s]
    for i in range(n):
        ans[lis[i]].add(i+1, 1)
    for _ in range(q):
        t, i, c = LS()
        i = int(i)
        if t == "1":
            ans[lis[i-1]].add(i, -1)
            ans[ord(c) - ord("a")].add(i, 1)
            lis[i-1] = ord(c) - ord("a")]
        else:
            l = i - 1
            r = int(c)
            res = 0
            for i in range(27):
                res += ans[i].sum(r) - ans[i].sum(l) > 0
            print(res)
    


    return


#main
if __name__ == '__main__':
    solve()

Submission status: Runtime Error

Solution code:
import java.util.*;

public class Main{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        long n = sc.nextLong();
        char[] s = sc.next().toCharArray();
        long q = sc.nextLong();
        
        for(int i = 0; i < q; i++){
            int a = sc.nextInt();
            if(a == 1){
                int b = sc.nextInt();
                char[] c = sc.next().toCharArray();
                
                s[b-1] = c[0];
            }else{
                int b = sc.nextInt();
                int c = sc.nextInt();
                
                HashSet<Character> hs = new HashSet<Character>();
                
                for(int j = b-1; j < c; j++){
                    hs.add(s[j]);
                }
                
                System.out.println(hs.size());
            }
        }
    }
}

Submission status: Runtime Error

Solution code:
import sys
from collections import *
import heapq
import math
import bisect
from itertools import permutations,accumulate,combinations,product
from fractions import gcd
import copy
def input():
    return sys.stdin.readline()[:-1]
def ruiseki(lst):
    return [0]+list(accumulate(lst))
mod=pow(10,9)+7

n=int(input())
s=input()
q=int(input())
query=[list(input().split()) for i in range(q)]


lst={}
for i in range(n):
    if not s[i] in lst:
        lst[s[i]]=[i]
    else:
        lst[s[i]].append(i)
erase={}
insert={}
# print(lst)
al=[chr(ord('a') + i) for i in range(26)]
for i in range(q):
    if query[i][0]=="1":
        one,j,c=query[i]
        j=int(j)
        if not s[i] in erase:
            erase[s[i]]=[j-1]
        else:
            erase[s[i]].append(j-1)
        
        if not c in insert:
            insert[c]=[j-1]
        else:
            insert[c].append(j-1)
    else:
        two,l,r=query[i]
        ans=0
        l=int(l)
        r=int(r)
        for i in range(26):
            tmp=0
            if al[i] in lst:
                tmp+=bisect.bisect_right(lst[al[i]],r-1)-bisect.bisect_left(lst[al[i]],l-1)
            if al[i] in erase:
                tmp-=bisect.bisect_right(erase[al[i]],r-1)-bisect.bisect_left(erase[al[i]],l-1)
            if al[i] in insert:
                tmp+=bisect.bisect_right(insert[al[i]],r-1)-bisect.bisect_left(insert[al[i]],l-1)
            if tmp>0:
                ans+=1
        print(ans)
    # print(erase)
    # print(insert)

Submission status: Runtime Error

Solution code:
import numpy as np

N = int(input())
S = input()

M = np.zeros((26, N+1))
for i in range(len(S)):
    M[:, i+1] += M[:, i]
    M[ord(S[i]) % 26, i+1] += 1

Q = int(input())
for i in range(Q):
    c, l, r = input().split()
    if c == '1':
        i = int(i)
        M[ord(S[i]) % 26, i:] -= 1
        M[ord(r) % 26, i:] += 1
    elif c == '2':
        l, r = int(l), int(r)
        print(np.sum((M[:, r] - M[:, l-1]) >= 1))

Submission status: Runtime Error

Solution code:
import sys
input=sys.stdin.readline
from string import ascii_lowercase

class BIT(): #1-indexed
    def __init__(self,n): #n: 要素数
        self.size=n
        self.bit=[0]*(n+1)
    def add(self,i,x): #i番目(1-indexed)にxを加算
        while i<=self.size:
            self.bit[i]+=x
            i+=i&-i
    def sum_1_to_i(self,i): #1番目からi番目(含む)までの総和(1-indexed)
        s=0
        while i>0:
            s+=self.bit[i]
            i-=i&-i
        return s
    def sum_i_to_j(self,i,j): #i番目からj番目(含む)までの総和(1-indexed)
        return self.sum_1_to_i(j)-self.sum_1_to_i(i-1)
    def reset(self): #初期化
        self.bit=[0]*(self.size+1)

def main():
    A=ascii_lowercase
    D=dict()
    for i,a in enumerate(A):
        D[a]=i
    n=int(input())
    S=list(input())
    L=[BIT(n) for _ in range(26)]
    for i,s in enumerate(S):
        k=D[s]
        L[k].add(i+1,1)
    q=int(input())
    for _ in range(q):
        k,a,b=input().split()
        if k=='1':
            i=int(a)-1
            s=S[i]
            l1=D[s]
            l2=D[b]
            L[l2].add(i+1,1)
            L[l1].add(i+1,-1)
        else:
            l=int(a); r=int(b)
            ans=0
            for i in range(26):
                ans+=L[i].sum_i_to_j(l,r)>0
            print(ans)
    
if __name__=='__main__':
    main()

Submission status: Runtime Error

Solution code:
import sys
from collections import *
import heapq
import math
import bisect
from itertools import permutations,accumulate,combinations,product
from fractions import gcd
import copy
def input():
    return sys.stdin.readline()[:-1]
def ruiseki(lst):
    return [0]+list(accumulate(lst))
mod=pow(10,9)+7

n=int(input())
s=input()
q=int(input())
query=[list(input().split()) for i in range(q)]


lst={}
for i in range(n):
    if not s[i] in lst:
        lst[s[i]]=[i]
    else:
        lst[s[i]].append(i)
erase={}
insert={}
# print(lst)
al=[chr(ord('a') + i) for i in range(26)]
for i in range(q):
    if query[i][0]=="1":
        one,i2,c=query[i]
        if not s[i] in erase:
            erase[s[i]]=[int(i2)]
        else:
            erase[s[i]].append(int(i2))
        if not c in insert:
            insert[c]=[int(i2)]
        else:
            insert[c].append(int(i2))
    else:
        two,l,r=query[i]
        ans=0
        l=int(l)
        r=int(r)
        for i in range(26):
            tmp=0
            if al[i] in lst:
                tmp+=bisect.bisect_right(lst[al[i]],r-1)-bisect.bisect_left(lst[al[i]],l-1)
            if al[i] in erase:
                tmp-=bisect.bisect_right(erase[al[i]],r-1)-bisect.bisect_left(erase[al[i]],l-1)
            if al[i] in insert:
                tmp+=bisect.bisect_right(insert[al[i]],r-1)-bisect.bisect_left(insert[al[i]],l-1)
            if tmp>0:
                ans+=1
        print(ans)
    # print(erase)
    # print(insert)

Submission status: Runtime Error

Solution code:
import sys
import bisect
n = int(sys.stdin.readline().strip())
s = list(sys.stdin.readline().strip())
alpha = "abcdefghijklmnopqrstuvwxyz"
dict = {i:[] for i in alpha}
for i, _s in enumerate(s):
    dict[_s].append(i)
q = int(sys.stdin.readline().strip())
for i in range(q):
    type, first, last = [i for i in sys.stdin.readline().split()]
    if type == "2":
        first = int(first)
        last = int(last)
        first -= 1
        last -= 1
        cnt = 0
        for ls in dict.values():
            if bisect.bisect_left(ls, first) != bisect.bisect_right(ls, last):
                cnt += 1
        print(cnt)
    else:
        _s = s[first]
        first = int(first)
        first -= 1
        dict[_s].pop(bisect.bisect_left(dict[_s], first))
        s[first] = last
        bisect.insort_left(dict[last], first)