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: Time Limit Exceeded

Solution code:
class SegmentTree(object):
    """
    セグメントツリー (0-indexed)

    1. 値の更新 O(logN)
    2. 区間クエリ O(logN)
    """
    def __BinOp(self, x, y):
        """ セグ木で使用する二項演算 """
        return x | y

    def __init__(self, init_ele, N:int):
        """
        セグ木を構築する

        init_ele: 単位元 
        N: 要素数
        """
        self.__init_ele = init_ele
        self.__n = 1
        while self.__n < N:
            self.__n <<= 1

        self.__dat = [init_ele] * (2 * self.__n)
    
    def update(self, k:int, x):
        """ k番目の値をxに変更する """
        k += self.__n - 1
        self.__dat[k] = x
        while k:
            k = (k - 1) // 2
            self.__dat[k] = self.__BinOp(
                self.__dat[k * 2 + 1], self.__dat[k * 2 + 2]
                )
    
    def query(self, p:int, q:int):
        """ 区間クエリ [p,q) """
        if q <= p: return self.__init_ele
        p += self.__n - 1
        q += self.__n - 2
        res = self.__init_ele
        while q - p > 1:
            if not (p & 1):
                res = self.__BinOp(res, self.__dat[p])
            if q & 1:
                res = self.__BinOp(res, self.__dat[q])
                q -= 1
            p = p // 2
            q = (q - 1) // 2
        res = self.__BinOp(res, self.__dat[p])
        if p != q: res = self.__BinOp(res, self.__dat[q])
        return res
    
    def get_num(self, k:int):
        """ k番目の値を取得する """
        k += self.__n - 1
        return self.__dat[k]

############################################################
N = int(input())

ST = SegmentTree(0, N)
for i, s in enumerate(list(input())):
    ST.update(i, 1 << (ord(s) - ord('a')))

Q = int(input())
for _ in range(Q):
    x,y,z = map(str,input().split())
    x = int(x); y = int(y)
    if x == 1:
        ST.update(y - 1, 1 << (ord(z) - ord('a')))
    else:
        z = int(z)
        print(bin(ST.query(y - 1, z)).count("1"))

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline


class SegmentTree():
    def __init__(self, S, n):
        self.size = n
        self.array = [set()] * (2**(self.size + 1) - 1)
        for i, c in enumerate(S):
            self.array[i + 2**self.size - 1] = {c}
        for i in range(2**self.size - 1)[::-1]:
            self.array[i] = self.array[2 * i + 1] | self.array[2 * i + 2]

    def subquery(self, l, r, k, i, j):
        if j <= l or r <= i:
            return set()
        elif l <= i and j <= r:
            return self.array[k]
        else:
            l_set = self.subquery(l, r, 2 * k + 1, i, (i + j) // 2)
            r_set = self.subquery(l, r, 2 * k + 2, (i + j) // 2, j)
            return l_set | r_set

    def query(self, l, r):
        return len(self.subquery(l, r, 0, 0, 2**self.size))

    def update(self, i, c):
        tmp = i + 2**self.size - 1
        self.array[tmp] = {c}
        while tmp > 0:
            tmp = (tmp - 1) // 2
            self.array[tmp] = self.array[2 * tmp + 1] | self.array[2 * tmp + 2]


n = int(input())
S = list(input())
S = [s for s in S]
segtree = SegmentTree(S, 19)
for _ in range(int(input())):
    t, i, c = input().split()
    if t == '1':
        segtree.update(int(i)-1, c)
    if t == '2':
        print(segtree.query(int(i)-1, int(c)))

Submission status: Time Limit Exceeded

Solution code:
class BIT:
    def __init__(self, N):
        self.tree = [0] * (N + 1)  # 1-indexed
        self.N = N

    def add(self, i, x):
        """tree[i]と関連個所にxを加える"""
        tree = self.tree
        N = self.N
        while i <= N:
            tree[i] += x
            i += i & (-i)

    def sum(self, i):
        tree = self.tree
        s = 0
        while i:
            s += tree[i]
            i -= i & (-i)
        return s


def main():
    from string import ascii_lowercase
    import sys
    input = sys.stdin.readline

    N = int(input())
    s = input().rstrip()
    Q = int(input())

    conv = {c: i for i, c in enumerate(ascii_lowercase)}
    s = [conv[c] for c in s]

    bs = [BIT(N) for _ in range(26)]
    for i, c in enumerate(s, 1):
        bs[c].add(i, 1)

    ans = []
    for _ in range(Q):
        it = iter(input().split())
        if next(it) == '1':
            # change
            i = int(next(it))  # 1-indexed
            c = conv[next(it)]

            p = s[i - 1]
            bs[p].add(i, -1)

            s[i - 1] = c
            bs[c].add(i, 1)

        else:
            # count
            l, r = map(int, it)
            cnt = 0
            for b in bs:
                cnt += int(b.sum(r) - b.sum(l - 1) > 0)
            ans.append(cnt)
    print(*ans, sep='\n')


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
class SegmentTree():
    # リストSの部分リストからなる集合を葉とするセグメント木
    def __init__(self, S, n):
        self.size = n
        self.array = [set()] * (2**(self.size + 1) - 1)
        for i, c in enumerate(S):
            self.array[i + 2**self.size - 1] = {c}
        for i in range(2**self.size - 1)[::-1]:
            self.array[i] = self.array[2 * i + 1] | self.array[2 * i + 2]

    def subquery(self, l, r, k, i, j):
        # 区間[i,j)の中で区間[l,r)の文字列の集合を返す
        if j <= l or r <= i:
            return set()
        elif l <= i and j <= r:
            return self.array[k]
        else:
            l_set = self.subquery(l, r, 2 * k + 1, i, (i + j) // 2)
            r_set = self.subquery(l, r, 2 * k + 2, (i + j) // 2, j)
            return l_set | r_set

    def query(self, l, r):
        # [l,r)に含まれる文字の種類数
        return len(self.subquery(l, r, 0, 0, 2**self.size))

    def update(self, i, c):
        # 配列のi番目をcに更新する
        tmp = i + 2**self.size - 1
        self.array[tmp] = {c}
        while tmp > 0:
            tmp = (tmp - 1) // 2
            self.array[tmp] = self.array[2 * tmp + 1] | self.array[2 * tmp + 2]


def main():
    n = int(input())
    S = list(input())
    S = [ord(s) for s in S]
    segtree = SegmentTree(S, 19)
    for _ in range(int(input())):
        t, i, c = input().split()
        if t == '1':
            segtree.update(int(i)-1, ord(c))
        if t == '2':
            print(segtree.query(int(i)-1, int(c)))


main()

Submission status: Time Limit Exceeded

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

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

Submission status: Time Limit Exceeded

Solution code:
class SegmentTree():
    # リストSの部分リストからなる集合を葉とするセグメント木
    def __init__(self, S, n):
        self.size = n
        self.array = [set()] * (2**(self.size + 1) - 1)
        for i, c in enumerate(S):
            self.array[i + 2**self.size - 1] = {c}
        for i in range(2**self.size - 1)[::-1]:
            self.array[i] = self.array[2 * i + 1] | self.array[2 * i + 2]

    def subquery(self, l, r, k, i, j):
        # 区間[i,j)の中で区間[l,r)の文字列の集合を返す
        if j <= l or r <= i:
            return set()
        elif l <= i and j <= r:
            return self.array[k]
        else:
            l_set = self.subquery(l, r, 2 * k + 1, i, (i + j) // 2)
            r_set = self.subquery(l, r, 2 * k + 2, (i + j) // 2, j)
            return l_set | r_set

    def query(self, l, r):
        # [l,r)に含まれる文字の種類数
        return len(self.subquery(l, r, 0, 0, 2**self.size))

    def update(self, i, c):
        # 配列のi番目をcに更新する
        tmp = i + 2**self.size - 1
        self.array[tmp] = {c}
        while tmp > 0:
            tmp = (tmp - 1) // 2
            self.array[tmp] = self.array[2 * tmp + 1] | self.array[2 * tmp + 2]


n = int(input())
S = list(input())
S = [ord(s) for s in S]
segtree = SegmentTree(S, 19)
for _ in range(int(input())):
    t, i, c = input().split()
    if t == '1':
        segtree.update(int(i)-1, ord(c))
    if t == '2':
        print(segtree.query(int(i)-1, int(c)))

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
n = int(input())
s = input()
q = int(input())
for i in range(q):
  que = input().split()
  if que[0] == '1':
    na,mu = que[1],que[2]
    na = int(na)
    s = s[:na-1] + mu + s[na:]
  else:
    na,mu = que[1],que[2]
    na,mu = int(na),int(mu)
    c = set(s[na-1:mu])
    print(len(c))

Submission status: Time Limit Exceeded

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 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 table_k // 2 > 0:
    #                     table_k //= 2
    #                     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 table_k // 2 > 0:
    #                 table_k //= 2
    #                 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("l should be less than or equals to r. got l:{} and r:{}".format(l, 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 = (table_l + 1)  // 2
    #             table_r = (table_r - 1) // 2
    #         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)
    
    # buf = []
    # for query in commands:
    #     execute_query(st, query, buf)
    # for elm in buf:
    #     print(elm)

    # 各クエリでの O(|alphabet|) が重いため TLE
    # a...z までの出現フラグを bit field で管理することを考える。そうすればある区間での出現文字を管理する数字たちを合わせる際には OR をとるだけて O(1) で高速に処理できる


    class SegTree:
        def __init__(self, size):
            self.size = size
            self.n0 = 2 ** (size - 1).bit_length()
            self.table = [0 for _ in range(2 * self.n0)]
        
        def update(self, k, new_char):
            'update char in a_k to new_char'
            table_k = k + self.n0 - 1
            new_num = 1 << (ord(new_char) - ord('a'))
            if self.table[table_k] != new_num:
                self.table[table_k] = new_num
                while table_k // 2 > 0:
                    table_k //= 2
                    self.table[table_k] = self.table[2 * table_k] | self.table[2 * table_k + 1]
        
        def range_set(self, l, r):
            'return integer that represents character set appeared in a_l to a_r'
            bit_field = 0
            table_l = l + self.n0 - 1
            table_r = r + self.n0 - 1
            if table_l > table_r:
                raise RuntimeError("l should be less than or equals to r. got l:{} and r:{}".format(l, r))
            while table_l < table_r:
                if table_l & 0b1 == 1:
                    bit_field |= self.table[table_l]
                if table_r & 0b1 == 0:
                    bit_field |= self.table[table_r]
                table_l = (table_l + 1)  // 2
                table_r = (table_r - 1) // 2
            if table_l == table_r:
                bit_field |= self.table[table_l]
            return bit_field


    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:])
            bit_field = seg_tree.range_set(i, j)
            buf.append(bin(bit_field)[2:].count('1'))

    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)
    
    buf = []
    for query in commands:
        execute_query(st, query, buf)
    for elm in buf:
        print(elm)


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

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("l should be less than or equals to r. got l:{} and r:{}".format(l, 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: Time Limit Exceeded

Solution code:
class SegmentTree():
    def segfunc(self, x, y):
        return x|y #関数
    
    def __init__(self, a): #a:リスト
        n = len(a)
        self.ide_ele = 0 #単位元
        self.num = 2**((n-1).bit_length()) #num:n以上の最小の2のべき乗
        self.seg = [self.ide_ele]*2*self.num
        
        #set_val
        for i in range(n):
            self.seg[i+self.num-1] = a[i]
        #built
        for i in range(self.num-2,-1,-1):
            self.seg[i] = self.segfunc(self.seg[2*i+1], self.seg[2*i+2])
        
        
    def update(self, k, s):
        x = 1<<(ord(s)-97)
        k += self.num-1
        self.seg[k] = x
        while k:
            k = (k-1)//2
            self.seg[k] = self.segfunc(self.seg[k*2+1], self.seg[k*2+2])
            
    def query(self, p, q):
        if q <= p:
            return self.ide_ele
        p += self.num-1
        q += self.num-2
        res = self.ide_ele
        while q - p > 1:
            if p&1 == 0:
                res = self.segfunc(res, self.seg[p])
            if q&1 == 1:
                res = self.segfunc(res, self.seg[q])
                q -= 1
            p = p//2
            q = (q-1)//2
        if p == q:
            res = self.segfunc(res,self.seg[p])
        else:
            res = self.segfunc(self.segfunc(res,self.seg[p]),self.seg[q])
        return res

def popcount(x):
    res = 0
    while x:
        res += x&1
        res >>= 1
    return res

N = int(input())
S = list(input())
for i in range(N):
    S[i] = 1<<(ord(S[i])-97)
Seg = SegmentTree(S)
Q = int(input())
for i in range(Q):
    x, y, z = input().split()
    if int(x) == 1:
        Seg.update(int(y)-1, z)
    else:
        print(popcount(Seg.query(int(y)-1, int(z))))

Submission status: Time Limit Exceeded

Solution code:
from bisect import insort, bisect_left

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

alphabet = "abcdefghijklmnopqrstuvwxyz"

bisects = {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: Time Limit Exceeded

Solution code:
from bisect import insort, bisect_left

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

alphabet = "abcdefghijklmnopqrstuvwxyz"

bisects = {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)
        del bisects[prev_c][prev_pos]
        insort(bisects[c], ind)
    else:
        l, r = int(a) - 1, int(b)
        cnt = 0
        for bs in bisects.values():
            if bisect_left(bs, l) != bisect_left(bs, r):
                cnt += 1
        print(cnt)

Submission status: Time Limit Exceeded

Solution code:
from bisect import insort, bisect_left

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

alphabet = "abcdefghijklmnopqrstuvwxyz"

bisects = {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():
            if bisect_left(bs, l) != bisect_left(bs, r):
                cnt += 1
        print(cnt)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
S = list(input())
Q = int(input())


class Bit:
    """1-indexed"""

    def __init__(self, n):
        self.size = n
        self.tree = [0] * (n + 1)

    def sum(self, i):
        s = 0
        while i > 0:
            s += self.tree[i]
            i -= i & -i
        return s

    def add(self, i, x):
        while i <= self.size:
            self.tree[i] += x
            i += i & -i


en2asc = lambda s: ord(s) - 97

Bits = [Bit(N) for _ in range(26)]
for i, s in enumerate(S):
    Bits[en2asc(s)].add(i + 1, 1)

for _ in range(Q):
    q = input().split()
    if q[0] == '1':
        i, c = int(q[1]), q[2]
        old = S[i - 1]
        Bits[en2asc(old)].add(i, -1)
        Bits[en2asc(c)].add(i, 1)
        S[i - 1] = c
    else:
        l, r = int(q[1]), int(q[2])
        ans = 0
        for b in Bits:
            ans += bool(b.sum(r) - b.sum(l - 1))
        print(ans)

Submission status: Time Limit Exceeded

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[ord(s)-OFS].append(i)

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

        s = ord(S[i])-OFS
        deli = bisect_left(D[s], i)
        del D[s][deli]
        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: Time Limit Exceeded

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[ord(s)-OFS].append(i)

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

        s = ord(S[i])-OFS
        D[s].pop(bisect_left(D[s], 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: Time Limit Exceeded

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 = [ord(s)-OFS for s in 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, ord(Q[2])-OFS
        s, S[i] = S[i], c

        D[s].pop(bisect_left(D[s], i))
        insort_left(D[c], i)

    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: Time Limit Exceeded

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

OFS = ord('a')
_, S, _, *Q = open(0).read().split()
S = [ord(s)-OFS for s in S]
Q = tuple(zip(*[iter(Q)]*3))

D = [[] for _ in [0]*26]

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

for q, *x in Q:
    if q == '1':
        i, c = int(x[0])-1, ord(x[1])-OFS
        s, S[i] = S[i], c

        D[s].pop(bisect_left(D[s], i))
        insort_left(D[c], i)

    else:
        l, r = int(x[0])-1, int(x[1])-1

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

        print(cnt)