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:
# coding: utf-8
import sys
#from operator import itemgetter
sysread = sys.stdin.readline
#from heapq import heappop, heappush
from collections import defaultdict
#from itertools import combinations
sys.setrecursionlimit(10**7)

def run():
    # import sys
    # A = list(map(int, sys.stdin.readline().split()))
    # all = sys.stdin.readlines()
    #N, *A = map(int, open(0))
    #N = int(input())
    ###
    def  bin_search(A,low_val):
        high = len(A) -1
        low = 0
        current = high // 2
        while high-low >1:
            if A[current] >= low_val:
                high = current
                current = (low + current) //2
            else:
                low = current
                current = (current + high) // 2
        return low, high, A[high]

    N = int(sysread())
    S = list('0'+input())
    dic = defaultdict(lambda:[])
    for idx, s in enumerate(S[1:],1):
        dic[s].append(idx)

    Q = int(sysread())
    queries = []
    for _ in range(Q):
        queries.append(sysread().split())

    for q,i,c in queries:
        if q == '1':
            i = int(i)
            old = S[i]
            dic[old].remove(i)
            if dic[c] == []:
                dic[c].append(i)
            else:
                l,h,_ = bin_search(dic[c], i)
                dic[c].insert(l,i)
            S[i] = c
        else:
            count = 0
            i,c = int(i), int(c)
            for key in dic.keys():
                tmp = dic[key]
                _,_,v = bin_search(tmp, i)
                if v <= c:
                    count += 1
            print(count)

if __name__ == "__main__":
    run()

Submission status: Runtime Error

Solution code:
# coding: utf-8
import sys
#from operator import itemgetter
sysread = sys.stdin.readline
#from heapq import heappop, heappush
from collections import defaultdict
#from itertools import combinations
sys.setrecursionlimit(10**7)

def run():
    def  bin_search(A,low_val):
        high = len(A) -1
        low = 0
        current = high // 2
        while high-low >1:
            if A[current] >= low_val:
                high = current
                current = (low + current) //2
            else:
                low = current
                current = (current + high) // 2
        return low, high, A[high]

    N = int(sysread())
    S = list('0'+input())
    dic = defaultdict(lambda:[])
    for idx, s in enumerate(S[1:],1):
        dic[s].append(idx)

    Q = int(sysread())
    queries = []
    for _ in range(Q):
        queries.append(sysread().split())

    for q,i,c in queries:
        if q == '1':
            i = int(i)
            old = S[i]
            dic[old].remove(i)
            if dic[c] == []:
                dic[c].append(i)
            else:
                l,h,_ = bin_search(dic[c], i)
                dic[c] = dic[c][:l+1]+[i]+dic[c][l+1:]
            S[i] = c
        else:
            count = 0
            i,c = int(i), int(c)
            for key in dic.keys():
                tmp = dic[key]
                _,_,v = bin_search(tmp, i)
                if v <= c:
                    count += 1
            print(count)

if __name__ == "__main__":
    run()

Submission status: Runtime Error

Solution code:
# coding: utf-8
import sys
#from operator import itemgetter
sysread = sys.stdin.readline
#from heapq import heappop, heappush
from collections import defaultdict
#from itertools import combinations
sys.setrecursionlimit(10**7)

def run():
    # import sys
    # A = list(map(int, sys.stdin.readline().split()))
    # all = sys.stdin.readlines()
    #N, *A = map(int, open(0))
    #N = int(input())
    ###
    def  bin_search(A,low_val):
        high = len(A) -1
        low = 0
        current = high // 2
        while high-low >1:
            if A[current] >= low_val:
                high = current
                current = (low + current) //2
            else:
                low = current
                current = (current + high) // 2
        return A[high]

    N = int(sysread())
    S = list('0'+input())
    dic = defaultdict(lambda:[])
    for idx, s in enumerate(S[1:],1):
        dic[s].append(idx)

    Q = int(sysread())
    queries = []
    for _ in range(Q):
        queries.append(sysread().split())

    for q,i,c in queries:
        if q == '1':
            i = int(i)
            old = S[i]
            dic[old].remove(i)
            dic[c].append(i)
            dic[c] = sorted(dic[c])
            S[i] = c
        else:
            count = 0
            i,c = int(i), int(c)
            for key in dic.keys():
                tmp = dic[key]
                if bin_search(tmp, i) <= c:
                    count += 1
            print(count)

if __name__ == "__main__":
    run()

Submission status: Runtime Error

Solution code:
# coding: utf-8
import sys
#from operator import itemgetter
sysread = sys.stdin.readline
#from heapq import heappop, heappush
from collections import defaultdict
#from itertools import combinations
sys.setrecursionlimit(10**7)

def run():
    # import sys
    # A = list(map(int, sys.stdin.readline().split()))
    # all = sys.stdin.readlines()
    #N, *A = map(int, open(0))
    #N = int(input())
    ###
    def  bin_search(A,low_val):
        high = len(A) -1
        low = 0
        current = high // 2
        while high-low >1:
            if A[current] >= low_val:
                high = current
                current = (low + current) //2
            else:
                low = current
                current = (current + high) // 2
        return A[high]

    N = int(sysread())A
    S = list('0'+input())
    dic = defaultdict(lambda:[])
    for idx, s in enumerate(S[1:],1):
        dic[s].append(idx)

    Q = int(sysread())
    queries = []
    for _ in range(Q):
        queries.append(sysread().split())

    for q,i,c in queries:
        if q == '1':
            i = int(i)
            old = S[i]
            dic[old].remove(i)
            dic[c].append(i)
            dic[c] = sorted(dic[c])
            S[i] = c
        else:
            count = 0
            i,c = int(i), int(c)
            for key in dic.keys():
                tmp = dic[key]
                if bin_search(tmp, i) <= c:
                    count += 1
            print(count)

if __name__ == "__main__":
    run()

Submission status: Runtime Error

Solution code:
# coding: utf-8
import sys
sysread = sys.stdin.readline
from collections import defaultdict
sys.setrecursionlimit(10**7)

def run():

    def  bin_search(A,low):
        high = len(A) -1
        low = 0
        current = high // 2
        while high-low >1:
            if A[current] >= low:
                high = current
                current = (low + current) //2
            else:
                low = current
                current = (current + high) // 2
        return A[high]

    N = int(sysread())
    S = list('0'+input())
    dic = defaultdict(lambda:[])
    for idx, s in enumerate(S[1:],1):
        dic[s].append(idx)

    Q = int(sysread())
    queries = []
    for _ in range(Q):
        queries.append(sysread().split())

    for q,i,c in queries:
        if q == '1':
            i = int(i)
            old = S[i]
            dic[old].remove(i)
            dic[c].append(i)
            dic[c] = sorted(dic[c])
            S[i] = c
        else:
            count = 0
            i,c = int(i), int(c)
            for key in dic.keys():
                tmp = dic[key]
                if bin_search(tmp, i) <= c:
                    count += 1
            print(count)

if __name__ == "__main__":
    run()

Submission status: Runtime Error

Solution code:
# https://atcoder.jp/contests/abc157/tasks/abc157_e
# セグメント木
# 各文字をビットに対応させる(セグ木を26本持っても良い)
import sys
read = sys.stdin.readline
from functools import reduce


def read_a_int():
    return int(read())


class SqrtDecomposedList:
    def __init__(self, ls, segfunc, identity_element):
        from math import sqrt
        from copy import copy
        self.f = segfunc  # queryのfunction
        self.ide = identity_element
        self.n = len(ls)
        self.ls = ls.copy()
        self.b = int(sqrt(self.n)) + 1
        self.bucket = [self.ide] * (self.b + 1)
        self._build()

    def _build(self):
        for d in range(self.b):
            self.bucket[d] = reduce(
                self.f, self.ls[(d * self.b):((d + 1) * self.b)], self.ide)
        # for i, v in enumerate(self.ls):
        #     self.bucket[i // self.b] = \
        #         self.f(v, self.bucket[i // self.b])

    def __getitem__(self, idx):
        return self.ls[idx]

    def update(self, i, x):
        '''i番目の要素をxに更新する O(√n)'''
        self.ls[i] = x
        s = i // self.b * self.b
        t = s + self.b
        # print(i, self.b, i // self.b, s, t)
        self.bucket[i // self.b] = reduce(self.f,
                                          self.ls[s:t], self.ide)

    def query(self, l, r):
        '''半開区間[l,r)で指定すること O(√n)'''
        if r - l < 2 * self.b:
            return reduce(self.f, self.ls[l:r])
        l_bucket = (l - 1) // self.b + 1
        r_bucket = r // self.b  # 半開区間なのでこれでいい
        ret = reduce(self.f, self.bucket[l_bucket:r_bucket], self.ide)
        ret = self.f(
            reduce(self.f, self.ls[l:(l_bucket * self.b)], self.ide),
            ret)
        ret = self.f(
            reduce(self.f, self.ls[(r_bucket * self.b):r], self.ide),
            ret)
        return ret


def segfunc(x, y):
    # 処理したい内容
    return x | y


def moji_to_bit(a):
    return 1 << (ord(a) - ord('a'))


def bit_to_sum(n):
    return sum([(n >> i) & 1 for i in range(n.bit_length())])


N = read_a_int()
S = read()[:-1]
S_bit = [moji_to_bit(s) for s in S]

# build segment tree
st = SqrtDecomposedList(S_bit, segfunc, 0)

Q = read_a_int()
for q in range(Q):
    com, a, b = read().split()
    if int(com) == 1:
        i, c = int(a) - 1, b
        st.update(i, moji_to_bit(c))
    else:
        l, r = int(a) - 1, int(b)
        print(bit_to_sum(st.query(l, r)))

Submission status: Runtime Error

Solution code:
# https://atcoder.jp/contests/abc157/tasks/abc157_e
# セグメント木
# 各文字をビットに対応させる(セグ木を26本持っても良い)
import sys
read = sys.stdin.readline
from functools import reduce

def read_a_int():
    return int(read())


class SqrtDecomposedList:
    def __init__(self, ls, segfunc, identity_element):
        from math import sqrt, floor
        from copy import copy
        self.f = segfunc  # queryのfunction
        self.ide = identity_element
        self.n = len(ls)
        self.ls = ls.copy()
        self.b = floor(sqrt(self.n))
        self.bucket = [self.ide] * self.b
        self._build()

    def _build(self):
        for d in range(self.b):
            self.bucket[d] = reduce(
                self.f, self.ls[(d * self.b):((d + 1) * self.b)], initial=self.ide)
        # for i, v in enumerate(self.ls):
        #     self.bucket[i // self.b] = \
        #         self.f(v, self.bucket[i // self.b])

    def __getitem__(self, idx):
        return self.ls[idx]

    def update(self, i, x):
        '''i番目の要素をxに更新する O(√n)'''
        self.ls[i] = x
        s = i // self.b * self.b
        t = s + self.b
        self.bucket[i // self.b] = reduce(self.f,
                                          self.ls[s:t], initial=self.ide)

    def query(self, l, r):
        '''半開区間[l,r)で指定すること O(√n)'''
        if r - l < 2 * self.b:
            return reduce(self.f, self.ls[l:r])
        l_bucket = (l - 1) // self.b + 1
        r_bucket = r // self.b  # 半開区間なのでこれでいい
        ret = reduce(self.f, self.bucket[l_bucket:r_bucket], initial=self.ide)
        ret = self.f(
            reduce(self.f, self.ls[l:(l_bucket * self.b)], initial=self.ide),
            ret)
        ret = self.f(
            reduce(self.f, self.ls[(r_bucket * self.b):r], initial=self.ide),
            ret)
        return ret


def segfunc(x, y):
    # 処理したい内容
    return x | y


def moji_to_bit(a):
    return 1 << (ord(a) - ord('a'))


def bit_to_sum(n):
    return sum([(n >> i) & 1 for i in range(n.bit_length())])


N = read_a_int()
S = read()[:-1]
S_bit = [moji_to_bit(s) for s in S]

# build segment tree
st = SqrtDecomposedList(S_bit, segfunc, 0)

Q = read_a_int()
for q in range(Q):
    com, a, b = read().split()
    if int(com) == 1:
        i, c = int(a) - 1, b
        st.update(i, moji_to_bit(c))
    else:
        l, r = int(a) - 1, int(b)
        print(bit_to_sum(st.query(l, r)))

Submission status: Runtime Error

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

for i in range(q):
    array = list(input())
    if array[0] == '1':
        a = int(array[2])
        s[a-1] = array[4]
    else:
        a = int(array[2]) - 1
        b = int(array[4]) - 1
        print(len(set(s[a:b + 1])))

Submission status: Runtime Error

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

import sys
# import math
# import re                                    # re.compile(pattern) => ptn obj; p.search(s), p.match(s), p.finditer(s) => match obj; p.sub(after, s)
# from collections import deque                # deque class. deque(L): dq.append(x), dq.appendleft(x), dq.pop(), dq.popleft(), dq.rotate()
from collections import defaultdict          # subclass of dict. defaultdict(facroty)
# from collections import Counter              # subclass of dict. Counter(iter): c.elements(), c.most_common(n), c.subtract(iter)
# from heapq import heapify, heappush, heappop # built-in list. heapify(L) changes list in-place to min-heap in O(n), heappush(heapL, x) and heappop(heapL) in O(lgn).
# from heapq import nlargest, nsmallest        # nlargest(n, iter[, key]) returns k-largest-list in O(n+klgn).
# from itertools import count, cycle, repeat   # count(start[,step]), cycle(iter), repeat(elm[,n])
# from itertools import groupby                # [(k, list(g)) for k, g in groupby('000112')] returns [('0',['0','0','0']), ('1',['1','1']), ('2',['2'])]
# from itertools import starmap                # starmap(pow, [[2,5], [3,2]]) returns [32, 9]
# from itertools import product                # product(iter, repeat=n)
# from itertools import accumulate             # accumulate(iter[, f])
# from functools import reduce                 # reduce(f, iter[, init])
# from functools import lru_cache              # @lrucache ...arguments of functions should be able to be keys of dict
# from bisect import bisect_left, bisect_right # bisect_left(a, x, lo=0, hi=len(a)) returns i such that all(val<x for val in a[lo:i]) and all(val>-=x for val in a[i:hi]).
# from copy import deepcopy                    # to copy multi-dimentional matrix without reference
# from fractions import gcd                    # for Python 3.4


def main():
    mod = 1000000007                  # 10^9+7
    inf = float('inf')
    sys.setrecursionlimit(10**6)    # 1000 -> 1000000
    def input(): return sys.stdin.readline().rstrip()
    def ii():  return int(input())
    def mi():  return map(int, input().split())
    def mi_0(): return map(lambda x: int(x)-1, input().split())
    def lmi(): return list(map(int, input().split()))
    def lmi_0(): return list(map(lambda x: int(x)-1, input().split()))
    def li():  return list(input())


    
    class SegTree:
        def __init__(self, size):
            self.size = size
            self.n0 = 2 ** (size - 1).bit_length()
            self.table = [defaultdict(int) for _ in range(2 * self.n0)]
        
        @classmethod
        def _p(cls, k):
            return k // 2
        @classmethod
        def _l(cls, k):
            return k * 2
        @classmethod
        def _r(cls, k):
            return k * 2 + 1
        @classmethod
        def accumulate_to_defaultdict(cls, dd, result_dd):
            for char, cnt in dd.items():
                if cnt > 0:
                    result_dd[char] += cnt
        
        
        def update(self, k, new_char):
            'update char in a_k to new_char'
            table_k = k + self.n0 - 1
            if self.table[table_k]:
                previous_char = self.table[table_k].popitem()[0]
                if previous_char != new_char:
                    self.table[table_k][new_char] += 1
                    while SegTree._p(table_k) > 0:
                        table_k = SegTree._p(table_k)
                        self.table[table_k][previous_char] -= 1
                        self.table[table_k][new_char] += 1
                else:
                    self.table[table_k][previous_char] = 1    # 戻すだけ
            else:
                self.table[table_k][new_char] += 1
                while SegTree._p(table_k) > 0:
                    table_k = SegTree._p(table_k)                
                    self.table[table_k][new_char] += 1

        
        def range_set(self, l, r):
            'return character counter dictionary ranging from a_l to a_r'
            d = defaultdict(int)
            table_l = l + self.n0 - 1
            table_r = r + self.n0 - 1
            if table_l > table_r:
                raise RuntimeError(f"l should be less than or equals to r. got l:{l} and r:{r}")
            while table_l < table_r:
                if table_l & 0b1 == 1:
                    SegTree.accumulate_to_defaultdict(self.table[table_l], d)
                if table_r & 0b1 == 0:
                    SegTree.accumulate_to_defaultdict(self.table[table_r], d)
                table_l = SegTree._p(table_l + 1)
                table_r = SegTree._p(table_r - 1)
            if table_l == table_r:
                SegTree.accumulate_to_defaultdict(self.table[table_l], d)
            return d
    
    
    def execute_query(seg_tree, L, buf):
        id = int(L[0])
        if id == 1:
            i = int(L[1])
            char = L[2]
            seg_tree.update(i, char)
        else:
            i, j = map(int, L[1:])
            d = seg_tree.range_set(i, j)
            buf.append(len(d))


    n = ii()
    s = input()
    q = ii()
    commands = []
    for _ in range(q):
        commands.append(input().split())

    st = SegTree(n)
    for i, char in enumerate(s):
        st.update(i+1, char)
    
    # for elm in st.table:
    #     print(elm)
    
    buf = []
    for query in commands:
        execute_query(st, query, buf)
    for elm in buf:
        print(elm)


if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
from bisect import insort, bisect_left

n = int(input())
s = list(input())
q = int(input())

alphabet = "abcdefghijklmnopqrstuvwxyz"

bisects = {chr(c):[] for c in alphabet}

for i,c in enumerate(s):
    insort(bisects[c], i)


for _ in range(q):
    command, a, b = input().split()
    if command == '1':
        ind, c = int(a)-1, b
        prev_c = s[ind]
        s[ind] = c
        prev_pos = bisect_left(bisects[prev_c], ind)
        bisects[prev_c].pop(prev_pos)
        insort(bisects[c], ind)
    else:
        l, r = int(a) - 1, int(b)
        cnt = 0
        for bs in bisects.values():
            ind = bisect_left(bs, l)
            if  ind < len(bs) and bs[ind] < r:
                cnt += 1
        print(cnt)

Submission status: Runtime Error

Solution code:
from bisect import insort, bisect_left

n = int(input())
s = list(input())
q = int(input())

alphabet = "abcdefghijklmnopqrstuvwxyz"

bisects = {chr(c):[] for c in alphabet}

for i,c in enumerate(s):
    insort(bisects[c], i)


for _ in range(q):
    command, a, b = input().split()
    if command == '1':
        ind, c = int(a)-1, b
        prev_c = s[ind]
        s[ind] = c
        prev_pos = bisect_left(bisects[prev_c], ind)
        bisects[prev_c].pop(prev_pos)
        insort(bisects[c], ind)
    else:
        l, r = int(a) - 1, int(b)
        cnt = 0
        for bs in bisects.values():
            ind = bisect_left(bs, l)
            if  bs[ind] < r:
                cnt += 1
        print(cnt)

Submission status: Runtime Error

Solution code:
# AtCoder Beginner Contest 157
# E - Simple String Queries
# https://atcoder.jp/contests/abc157/tasks/abc157_e
from bisect import bisect_left, insort_left
import sys
input = sys.stdin.readline
OFS = ord('a')
_ = input()
S = list(input()[:-1])

D = [[] for _ in [0]*26]
for i, s in enumerate(S):
    D[s].append(i)

for _ in [0]*int(input()):
    Q = input()[:-1].split()
    if Q[0] == '1':
        i, c = int(Q[1])-1, Q[2]

        D[s].pop(bisect_left(D[S[i]], i))
        insort_left(D[ord(c)-OFS], i)
        S[i] = c

    else:
        l, r = int(Q[1])-1, int(Q[2])-1

        cnt = 0
        for L in D:
            i = bisect_left(L, l)
            if i < len(L) and L[i] <= r:
                cnt += 1

        print(cnt)

Submission status: Runtime Error

Solution code:
# AtCoder Beginner Contest 157
# E - Simple String Queries
# https://atcoder.jp/contests/abc157/tasks/abc157_e
from bisect import bisect_left, insort_left
from collections import defaultdict


_, S, _, *Q = open(0).read().split()
S = list(S)
Q = tuple(zip(*[iter(Q)]*3))

D = defaultdict(list)

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

for q, *x in Q:
    if int(q) == 1:
        i, c = x
        i = int(i) - 1

        d = D[S[i]]
        i = bisect_left(d, i)
        d.pop(i)

        d = D[c]
        insort_left(d, i)

        S[i] = c

    else:
        l, r = map(int, x)
        l -= 1
        r -= 1
        cnt = 0
        for L in D.values():
            i = bisect_left(L, l)
            if i == len(L):
                continue
            if L[i] <= r:
                cnt += 1

        print(cnt)

Submission status: Runtime Error

Solution code:
# AtCoder Beginner Contest 157
# E - Simple String Queries
# https://atcoder.jp/contests/abc157/tasks/abc157_e
from bisect import bisect_left, insort_left
from collections import defaultdict


_, S, _, *Q = open(0).read().split()
Q = tuple(zip(*[iter(Q)]*3))

D = defaultdict(list)

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

for q, *x in Q:
    if int(q) == 1:
        i, c = x
        i = int(i) - 1

        d = D[S[i]]
        i = bisect_left(d, i)
        d.pop(i)

        d = D[c]
        insort_left(d, i)

    else:
        l, r = map(int, x)
        l -= 1
        r -= 1
        cnt = 0
        for L in D.values():
            i = bisect_left(L, l)
            if i == len(L):
                continue
            if L[i] <= r:
                cnt += 1

        print(cnt)

Submission status: Runtime Error

Solution code:
# AtCoder Beginner Contest 157
# E - Simple String Queries
# https://atcoder.jp/contests/abc157/tasks/abc157_e
from bisect import bisect_left, bisect, insort_left, insort
from collections import defaultdict


_, S, _, *Q = open(0).read().split()
Q = tuple(zip(*[iter(Q)]*3))

D = defaultdict(list)

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

for q, *x in Q:
    if int(q) == 1:
        i, c = x
        i = int(i) - 1

        d = D[S[i]]
        i = bisect_left(d, i)
        d.pop(i)

        d = D[c]
        insort(d, i)

    else:
        l, r = map(int, x)
        l -= 1
        r -= 1
        cnt = 0
        for L in D.values():
            i = bisect_left(L, l)
            if i == len(L):
                continue
            if L[i] <= r:
                cnt += 1

        print(cnt)

Submission status: Runtime Error

Solution code:
import bisect
n = int(input().strip())
S = input().strip()
L=[[] for _ in range(26)]
for i,s in enumerate(S):
    L[ord(s)-ord("a")].append(i)

q = int(input().strip())
for _ in range(q):
    query=input().strip().split()
    if query[0]=="1":
        i=int(query[1])
        i-=1
        c=query[2]
        if S[i]!=c:
            delInd=bisect.bisect_left(L[ord(S[i])-ord("a")],i)
            del L[ord(S[i])-ord("a")][delInd]
            bisect.insort(L[ord(c)-ord("a")], i)
            S[i]=c
    else:
        l,r=map(int,[query[1],query[2]])
        l-=1; r-=1
        ans=0
        for j in range(26):
            ind=bisect.bisect_left(L[j],l)
            if ind<len(L[j]) and L[j][ind]<=r:
                ans+=1
        print(ans)

Submission status: Runtime Error

Solution code:
import bisect
n = int(input().strip())
S = input().strip()
L=[[] for _ in range(26)]
for i,s in enumerate(S):
    L[ord(s)-ord("a")].append(i)

q = int(input().strip())
for _ in range(q):
    query=input().strip().split()
    if query[0]=="1":
        i=int(query[1])
        i-=1
        c=query[2]
        if S[i]!=c:
            delInd=bisect.bisect_left(L[ord(S[i])-ord("a")],i)
            del L[ord(S[i])-ord("a")][delInd]
            bisect.insort(L[ord(c)-ord("a")], i)
    else:
        l,r=map(int,[query[1],query[2]])
        l-=1; r-=1
        ans=0
        for j in range(26):
            ind=bisect.bisect_left(L[j],l)
            if ind<len(L[j]) and L[j][ind]<=r:
                ans+=1
        print(ans)

Submission status: Runtime Error

Solution code:
import sys
sys.setrecursionlimit(1000000)
def input():
    return sys.stdin.readline()

n = int(input())
s = input()
q = int(input())


class SegmentTree:
    def __init__(self, a, func=max, one=-10 ** 18):
        self.logn = (len(a) - 1).bit_length()
        self.n = 1 << self.logn
        self.func = func
        self.one = one

        self.b = [self.one] * (2 * self.n - 1)
        for i, j in enumerate(a):
            self.b[i + self.n - 1] = j
        for i in reversed(range(self.n - 1)):
            self.b[i] = self.func(self.b[i * 2 + 1], self.b[i * 2 + 2])

    def get_item(self, i):
        return self.b[i + self.n - 1]

    def update(self, index, x):
        i = index + self.n - 1
        self.b[i] = x
        while i != 0:
            i = (i - 1) // 2
            self.b[i] = self.func(self.b[i * 2 + 1], self.b[i * 2 + 2])

    def update_func(self, index, x):
        i = index + self.n - 1
        self.b[i] = self.func(self.b[i], x)
        while i != 0:
            i = (i - 1) // 2
            self.b[i] = self.func(self.b[i * 2 + 1], self.b[i * 2 + 2])

    def get_segment(self, l, r, i=0):
        j = i - (1 << ((i + 1).bit_length() - 1))+1
        length = 1 << (self.logn - (i + 1).bit_length() + 1)
        ll = j * length
        rr = (j + 1) * length
        if l <= ll and rr <= r:
            return self.b[i]
        elif rr <= l or r <= ll:
            return self.one
        else:
            return self.func(self.get_segment(l, r, i * 2 + 1),
                             self.get_segment(l, r, i * 2 + 2))


abc = "abcdefghijklmnopqrstuvwxyz"
seg = [SegmentTree([0] * n, int.__add__, False) for _ in range(26)]
string = []
for i, j in enumerate(s):
    k = abc.index(j)
    seg[k].update(i, 1)
    string.append(k)


for _ in range(q):
    q, i, j = input().split()
    if q == "1":
        i = int(i) - 1
        seg[string[i]].update(i, 0)
        seg[abc.index(j)].update(i, 1)
        string[i] = j
    else:
        ans = 0
        for k in seg:
            if k.get_segment(int(i) - 1, int(j)) > 0:
                ans += 1
        print(ans)

Submission status: Runtime Error

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


class SegmentTree:
    def __init__(self, a, func=max, one=-10 ** 18):
        self.logn = (len(a) - 1).bit_length()
        self.n = 1 << self.logn
        self.func = func
        self.one = one

        self.b = [self.one] * (2 * self.n - 1)
        for i, j in enumerate(a):
            self.b[i + self.n - 1] = j
        for i in reversed(range(self.n - 1)):
            self.b[i] = self.func(self.b[i * 2 + 1], self.b[i * 2 + 2])

    def get_item(self, i):
        return self.b[i + self.n - 1]

    def update(self, index, x):
        i = index + self.n - 1
        self.b[i] = x
        while i != 0:
            i = (i - 1) // 2
            self.b[i] = self.func(self.b[i * 2 + 1], self.b[i * 2 + 2])

    def update_func(self, index, x):
        i = index + self.n - 1
        self.b[i] = self.func(self.b[i], x)
        while i != 0:
            i = (i - 1) // 2
            self.b[i] = self.func(self.b[i * 2 + 1], self.b[i * 2 + 2])

    def get_segment(self, l, r, i=0):
        j = i - (1 << ((i + 1).bit_length() - 1))+1
        length = 1 << (self.logn - (i + 1).bit_length() + 1)
        ll = j * length
        rr = (j + 1) * length
        if l <= ll and rr <= r:
            return self.b[i]
        elif rr <= l or r <= ll:
            return self.one
        else:
            return self.func(self.get_segment(l, r, i * 2 + 1),
                             self.get_segment(l, r, i * 2 + 2))


abc = "abcdefghijklmnopqrstuvwxyz"
seg = [SegmentTree([0] * n, int.__add__, False) for _ in range(26)]
string = []
for i, j in enumerate(s):
    k = abc.index(j)
    seg[k].update(i, 1)
    string.append(k)


for _ in range(q):
    q, i, j = input().split()
    if q == "1":
        i = int(i) - 1
        seg[string[i]].update(i, 0)
        seg[abc.index(j)].update(i, 1)
        string[i] = j
    else:
        ans = 0
        for k in seg:
            if k.get_segment(int(i) - 1, int(j)) > 0:
                ans += 1
        print(ans)

Submission status: Runtime Error

Solution code:
def main():
    n = int(input())
    a = ord("a")
    orda = lambda x: ord(x)-a
    s = list(map(orda, list(input())))
    q = int(input())
    bits = [BIT(n) for _ in range(26)]
    for i, si in enumerate(s, 1):
        bits[si].add(i, 1)
    for _ in range(q):
        t, i, c = input().split()
        i = int(i)
        if t == "1":
            bits[s[i-1]].add(i, -1)
            bits[ord(c)-a].add(i, 1)
            si[i-1] = ord(c)-a
        else:
            c = int(c)
            cnt = 0
            for bit in bits:
                is_in = bit.sum_(c) - bit.sum_(i-1)
                if is_in:
                    cnt += 1
            print(cnt)
            
            
class BIT:
    __slots__ = ["length", "data"]
    def __init__(self, length):
        self.data = [0]*(length+1)
        self.length = length
    
    def add(self, i, x):
        while i < self.length+1:
            self.data[i] += x
            i += i&-i
    
    def sum_(self, i):
        x = 0
        while i > 0:
            x += self.data[i]
            i -= i&-i
        return x


if __name__ == "__main__":
    main()