Problem:


Score : 600 points

Problem Statement

We have N colored balls arranged in a row from left to right; the color of the i-th ball from the left is c_i.

You are given Q queries. The i-th query is as follows: how many different colors do the l_i-th through r_i-th balls from the left have?

Constraints

1\leq N,Q \leq 5 \times 10^5

1\leq c_i \leq N

1\leq l_i \leq r_i \leq N

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N Q
c_1 c_2 \cdots c_N
l_1 r_1
l_2 r_2
:
l_Q r_Q

Output

Print Q lines. The i-th line should contain the response to the i-th query.

Sample Input 1

4 3
1 2 1 3
1 3
2 4
3 3

Sample Output 1

2
3
1

The 1-st, 2-nd, and 3-rd balls from the left have the colors 1, 2, and 1 - two different colors.

The 2-st, 3-rd, and 4-th balls from the left have the colors 2, 1, and 3 - three different colors.

The 3-rd ball from the left has the color 1 - just one color.

Sample Input 2

10 10
2 5 6 5 2 1 7 9 7 2
5 5
2 4
6 7
2 2
7 8
7 9
1 8
6 9
8 10
6 8

Sample Output 2

1
2
2
1
2
2
6
3
3
3



Sample input:
4 3
1 2 1 3
1 3
2 4
3 3


Sample output:
2
3
1

Submission status: Time Limit Exceeded

Solution code:
"""
    Satwik_Tiwari ;) .
    12th Sept , 2020  - Saturday
"""

#===============================================================================================
#importing some useful libraries.
from __future__ import division, print_function

# from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase

# from itertools import *
# import bisect
# from heapq import *
# from math import *
# from copy import *
# from collections import deque
# from collections import Counter as counter  # Counter(list)  return a dict with {key: count}
# from itertools import combinations as comb # if a = [1,2,3] then print(list(comb(a,2))) -----> [(1, 2), (1, 3), (2, 3)]
# from itertools import permutations as permutate
# from bisect import bisect_left as bl

#If the element is already present in the list,
# the left most position where element has to be inserted is returned.

# from bisect import bisect_right as br
# from bisect import bisect

#If the element is already present in the list,
# the right most position where element has to be inserted is returned

#==============================================================================================
#fast I/O region
BUFSIZE = 8192


class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)


class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")


def print(*args, **kwargs):
    """Prints the values to a stream, or to sys.stdout by default."""
    sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
    at_start = True
    for x in args:
        if not at_start:
            file.write(sep)
        file.write(str(x))
        at_start = False
    file.write(kwargs.pop("end", "\n"))
    if kwargs.pop("flush", False):
        file.flush()


if sys.version_info[0] < 3:
    sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
    sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)

# inp = lambda: sys.stdin.readline().rstrip("\r\n")

#===============================================================================================
### START ITERATE RECURSION ###
# from types import GeneratorType
# def iterative(f, stack=[]):
#   def wrapped_func(*args, **kwargs):
#     if stack: return f(*args, **kwargs)
#     to = f(*args, **kwargs)
#     while True:
#       if type(to) is GeneratorType:
#         stack.append(to)
#         to = next(to)
#         continue
#       stack.pop()
#       if not stack: break
#       to = stack[-1].send(to)
#     return to
#   return wrapped_func
#### END ITERATE RECURSION ####

#===============================================================================================
#some shortcuts

mod = 1000000007
def inp(): return sys.stdin.readline().rstrip("\r\n") #for fast input
def out(var): sys.stdout.write(str(var))  #for fast output, always take string
def lis(): return list(map(int, inp().split()))
def stringlis(): return list(map(str, inp().split()))
def sep(): return map(int, inp().split())
def strsep(): return map(str, inp().split())
# def graph(vertex): return [[] for i in range(0,vertex+1)]
def zerolist(n): return [0]*n
def nextline(): out("\n")  #as stdout.write always print sring.
def testcase(t):
    for pp in range(t):
        solve(pp)
def printlist(a) :
    for p in range(0,len(a)):
        out(str(a[p]) + ' ')
def google(p):
    print('Case #'+str(p)+': ',end='')
def lcm(a,b): return (a*b)//gcd(a,b)
def power(x, y, p) :
    res = 1     # Initialize result
    x = x % p  # Update x if it is more , than or equal to p
    if (x == 0) :
        return 0
    while (y > 0) :
        if ((y & 1) == 1) : # If y is odd, multiply, x with result
            res = (res * x) % p

        y = y >> 1      # y = y/2
        x = (x * x) % p
    return res
def ncr(n,r): return factorial(n)//(factorial(r)*factorial(max(n-r,1)))
def isPrime(n) :
    if (n <= 1) : return False
    if (n <= 3) : return True
    if (n % 2 == 0 or n % 3 == 0) : return False
    i = 5
    while(i * i <= n) :
        if (n % i == 0 or n % (i + 2) == 0) :
            return False
        i = i + 6
    return True

#===============================================================================================
# code here ;))
class BIT:
    def __init__(self,n):
        self.n = n
        self.tree = [0]*(n+1)

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

    def update(self,x,k):
        while(x<=self.n):
            self.tree[x]+=k
            x+=x&(-x)

    def build(self,a):
        for i in range(len(a)):
            k = a[i]
            x = i+1
            while(x<=self.n):
                self.tree[x]+=k
                x+=x&(-x)

def solve(case):
    n,q = sep()
    c = lis()
    query = []
    for i in range(q):
        l,r = sep()
        query.append((r,l,i))

    query.sort()
    bit = BIT(n)
    lastvis = [-1]*(n+1)
    ind = 0
    ans = [0]*q
    for i in range(n):
        if(lastvis[c[i]] != -1):
            bit.update(lastvis[c[i]]+1,-1)

        lastvis[c[i]] = i
        bit.update(i+1,1)
        while(ind<q and query[ind][0] == i+1):
            ans[query[ind][2]] = (bit.sum(i+1) - bit.sum(query[ind][1]-1))
            ind+=1

    print('\n'.join(str(ans[i]) for i in range(len(ans))))

testcase(1)
# testcase(int(inp()))

Submission status: Time Limit Exceeded

Solution code:
"""
    Satwik_Tiwari ;) .
    12th Sept , 2020  - Saturday
"""

#===============================================================================================
#importing some useful libraries.
from __future__ import division, print_function

# from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase

# from itertools import *
# import bisect
# from heapq import *
# from math import *
# from copy import *
# from collections import deque
# from collections import Counter as counter  # Counter(list)  return a dict with {key: count}
# from itertools import combinations as comb # if a = [1,2,3] then print(list(comb(a,2))) -----> [(1, 2), (1, 3), (2, 3)]
# from itertools import permutations as permutate
# from bisect import bisect_left as bl

#If the element is already present in the list,
# the left most position where element has to be inserted is returned.

# from bisect import bisect_right as br
# from bisect import bisect

#If the element is already present in the list,
# the right most position where element has to be inserted is returned

#==============================================================================================
#fast I/O region
BUFSIZE = 8192


class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)


class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")


def print(*args, **kwargs):
    """Prints the values to a stream, or to sys.stdout by default."""
    sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
    at_start = True
    for x in args:
        if not at_start:
            file.write(sep)
        file.write(str(x))
        at_start = False
    file.write(kwargs.pop("end", "\n"))
    if kwargs.pop("flush", False):
        file.flush()


if sys.version_info[0] < 3:
    sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
    sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)

# inp = lambda: sys.stdin.readline().rstrip("\r\n")

#===============================================================================================
### START ITERATE RECURSION ###
# from types import GeneratorType
# def iterative(f, stack=[]):
#   def wrapped_func(*args, **kwargs):
#     if stack: return f(*args, **kwargs)
#     to = f(*args, **kwargs)
#     while True:
#       if type(to) is GeneratorType:
#         stack.append(to)
#         to = next(to)
#         continue
#       stack.pop()
#       if not stack: break
#       to = stack[-1].send(to)
#     return to
#   return wrapped_func
#### END ITERATE RECURSION ####

#===============================================================================================
#some shortcuts

mod = 1000000007
def inp(): return sys.stdin.readline().rstrip("\r\n") #for fast input
def out(var): sys.stdout.write(str(var))  #for fast output, always take string
def lis(): return list(map(int, inp().split()))
def stringlis(): return list(map(str, inp().split()))
def sep(): return map(int, inp().split())
def strsep(): return map(str, inp().split())
# def graph(vertex): return [[] for i in range(0,vertex+1)]
def zerolist(n): return [0]*n
def nextline(): out("\n")  #as stdout.write always print sring.
def testcase(t):
    for pp in range(t):
        solve(pp)
def printlist(a) :
    for p in range(0,len(a)):
        out(str(a[p]) + ' ')
def google(p):
    print('Case #'+str(p)+': ',end='')
def lcm(a,b): return (a*b)//gcd(a,b)
def power(x, y, p) :
    res = 1     # Initialize result
    x = x % p  # Update x if it is more , than or equal to p
    if (x == 0) :
        return 0
    while (y > 0) :
        if ((y & 1) == 1) : # If y is odd, multiply, x with result
            res = (res * x) % p

        y = y >> 1      # y = y/2
        x = (x * x) % p
    return res
def ncr(n,r): return factorial(n)//(factorial(r)*factorial(max(n-r,1)))
def isPrime(n) :
    if (n <= 1) : return False
    if (n <= 3) : return True
    if (n % 2 == 0 or n % 3 == 0) : return False
    i = 5
    while(i * i <= n) :
        if (n % i == 0 or n % (i + 2) == 0) :
            return False
        i = i + 6
    return True

#===============================================================================================
# code here ;))
# class BIT:
#     def __init__(self,n):
#         self.n = n
#         self.tree = [0]*(n+1)
#
#     def sum(self,x):
#         sum = 0
#         while(x>0):
#             sum+=self.tree[x]
#             x-=x&(-x)
#         return sum
#
#     def update(self,x,k):
#         while(x<=self.n):
#             self.tree[x]+=k
#             x+=x&(-x)
#
#     def build(self,a):
#         for i in range(len(a)):
#             k = a[i]
#             x = i+1
#             while(x<=self.n):
#                 self.tree[x]+=k
#                 x+=x&(-x)

class BIT:
    def __init__(self, n):
        self.n = n
        self.data = [0]*(n+1)

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

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

    def get(self, i, j):
        return self.to_sum(j)-self.to_sum(i-1)

def solve(case):
    n,q = sep()
    c = lis()
    query = []
    for i in range(q):
        l,r = sep()
        query.append((r,l,i))

    query = sorted(query)
    bit = BIT(n)
    lastvis = [-1]*(n+1)
    ind = 0
    ans = [0]*q
    for i in range(n):
        if(lastvis[c[i]] != -1):
            bit.add(lastvis[c[i]]+1,-1)

        lastvis[c[i]] = i
        bit.add(i+1,1)
        while(ind<q and query[ind][0] == i+1):
            ans[query[ind][2]] = (bit.to_sum(i+1) - bit.to_sum(query[ind][1]-1))
            ind+=1

    print('\n'.join(str(ans[i]) for i in range(len(ans))))

testcase(1)
# testcase(int(inp()))

Submission status: Time Limit Exceeded

Solution code:
"""
    Satwik_Tiwari ;) .
    12th Sept , 2020  - Saturday
"""

#===============================================================================================
#importing some useful libraries.
from __future__ import division, print_function

# from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase

# from itertools import *
# import bisect
# from heapq import *
# from math import *
# from copy import *
# from collections import deque
# from collections import Counter as counter  # Counter(list)  return a dict with {key: count}
# from itertools import combinations as comb # if a = [1,2,3] then print(list(comb(a,2))) -----> [(1, 2), (1, 3), (2, 3)]
# from itertools import permutations as permutate
# from bisect import bisect_left as bl

#If the element is already present in the list,
# the left most position where element has to be inserted is returned.

# from bisect import bisect_right as br
# from bisect import bisect

#If the element is already present in the list,
# the right most position where element has to be inserted is returned

#==============================================================================================
#fast I/O region
BUFSIZE = 8192


class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)


class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")


def print(*args, **kwargs):
    """Prints the values to a stream, or to sys.stdout by default."""
    sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
    at_start = True
    for x in args:
        if not at_start:
            file.write(sep)
        file.write(str(x))
        at_start = False
    file.write(kwargs.pop("end", "\n"))
    if kwargs.pop("flush", False):
        file.flush()


if sys.version_info[0] < 3:
    sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
    sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)

# inp = lambda: sys.stdin.readline().rstrip("\r\n")

#===============================================================================================
### START ITERATE RECURSION ###
# from types import GeneratorType
# def iterative(f, stack=[]):
#   def wrapped_func(*args, **kwargs):
#     if stack: return f(*args, **kwargs)
#     to = f(*args, **kwargs)
#     while True:
#       if type(to) is GeneratorType:
#         stack.append(to)
#         to = next(to)
#         continue
#       stack.pop()
#       if not stack: break
#       to = stack[-1].send(to)
#     return to
#   return wrapped_func
#### END ITERATE RECURSION ####

#===============================================================================================
#some shortcuts

mod = 1000000007
def inp(): return sys.stdin.readline().rstrip("\r\n") #for fast input
def out(var): sys.stdout.write(str(var))  #for fast output, always take string
def lis(): return list(map(int, inp().split()))
def stringlis(): return list(map(str, inp().split()))
def sep(): return map(int, inp().split())
def strsep(): return map(str, inp().split())
# def graph(vertex): return [[] for i in range(0,vertex+1)]
def zerolist(n): return [0]*n
def nextline(): out("\n")  #as stdout.write always print sring.
def testcase(t):
    for pp in range(t):
        solve(pp)
def printlist(a) :
    for p in range(0,len(a)):
        out(str(a[p]) + ' ')
def google(p):
    print('Case #'+str(p)+': ',end='')
def lcm(a,b): return (a*b)//gcd(a,b)
def power(x, y, p) :
    res = 1     # Initialize result
    x = x % p  # Update x if it is more , than or equal to p
    if (x == 0) :
        return 0
    while (y > 0) :
        if ((y & 1) == 1) : # If y is odd, multiply, x with result
            res = (res * x) % p

        y = y >> 1      # y = y/2
        x = (x * x) % p
    return res
def ncr(n,r): return factorial(n)//(factorial(r)*factorial(max(n-r,1)))
def isPrime(n) :
    if (n <= 1) : return False
    if (n <= 3) : return True
    if (n % 2 == 0 or n % 3 == 0) : return False
    i = 5
    while(i * i <= n) :
        if (n % i == 0 or n % (i + 2) == 0) :
            return False
        i = i + 6
    return True

#===============================================================================================
# code here ;))
class BIT:
    def __init__(self,n):
        self.n = n
        self.tree = [0]*(n+1)

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

    def update(self,x,k):
        while(x<=self.n):
            self.tree[x]+=k
            x+=x&(-x)

    def build(self,a):
        for i in range(len(a)):
            k = a[i]
            x = i+1
            while(x<=self.n):
                self.tree[x]+=k
                x+=x&(-x)

def solve(case):
    n,q = sep()
    c = lis()
    query = []
    for i in range(q):
        l,r = sep()
        query.append((r,l,i))

    query = sorted(query)
    bit = BIT(n)
    lastvis = [-1]*(n+1)
    ind = 0
    ans = [0]*q
    for i in range(n):
        if(lastvis[c[i]] != -1):
            bit.update(lastvis[c[i]]+1,-1)

        lastvis[c[i]] = i
        bit.update(i+1,1)
        while(ind<q and query[ind][0] == i+1):
            ans[query[ind][2]] = (bit.sum(i+1) - bit.sum(query[ind][1]-1))
            ind+=1

    for i in range(q):
        print(ans[i])

testcase(1)
# testcase(int(inp()))

Submission status: Time Limit Exceeded

Solution code:
from collections import defaultdict

n, q = map(int, input().split())
c = list(map(int, input().split()))

d = defaultdict(int)

result = []
for i, x in enumerate(c):
    if d[x] > 0:
        result.append((d[x], i + 1))
    d[x] = i + 1

for _ in range(q):
    l, r = map(int, input().split())
    whole = r - l + 1
    minus = 0
    for (x, y) in result:
        if l <= x and y <= r:
            minus += 1
    print(whole - minus)

Submission status: Time Limit Exceeded

Solution code:
class BIT:
    def __init__(self, n):
        self.n = n
        self.data = [0]*(n+1)
 
    def to_sum(self, i):
        s = 0
        while i > 0:
            s += self.data[i]
            i -= (i & -i)
        return s
 
    def add(self, i, x):
        while i <= self.n:
            self.data[i] += x
            i += (i & -i)
 
    def get(self, i, j):
        return self.to_sum(j)-self.to_sum(i-1)

import sys
input = sys.stdin.readline
N,Q = map(int,input().split())
C = list(map(int,input().split()))
#print(C)
LR = []
ans = [0 for _ in range(Q)]
for i in range(Q):
  temp= list(map(int,input().split()))
  LR.append((temp,i)) #クエリとID
LR.sort(key=lambda x : x[0][1]) #右端で昇順にソート
#print(LR)
CMAX = max(C)
Tree = BIT(N)
last = [-1 for _ in range(CMAX)] #色を0index
left,right = LR[0][0]
for j in range(right):
  mae = last[C[j]-1]
  last[C[j]-1] = j
  if mae !=-1:
    Tree.add(mae+1,-1) #BITは1から
  Tree.add(last[C[j]-1]+1,1) #BITは1から
  #print(Tree.get(left,right))
#print(last)
D = []
#for i in range(1,N+1):
#  detemp = Tree.get(i,i)
#  D.append(detemp)
#print(D)

temp = Tree.get(left,right)
ID = LR[0][1]
ans[ID] = temp
lastright = right  
#print(Tree.get(left,right))
for i in range(1,Q):
  left,right = LR[i][0]
  #print(right,lastright)
  if lastright < right:
    for j in range(lastright,right):
      mae = last[C[j]-1]
      last[C[j]-1] = j
      #print(C[j],mae,j,last[C[j]-1] )
      if mae !=-1:
        #rint(C[j],"A")
        Tree.add(mae+1,-1) #BITは1index
      Tree.add(j+1,1) #BITは1index
  temp = Tree.get(left,right)
  ID = LR[i][1]
  ans[ID] = temp
  #lastright = max(right,lastright)
  #print(last)


print(*ans,sep="\n")

Submission status: Time Limit Exceeded

Solution code:
from itertools import accumulate
import copy

n, q = map(int, input().split())
c = list(map(int, input().split()))

# cとの0〜var - 1の変換表を作る
cc = copy.deepcopy(c)
cc.sort()
processed = [-1]

for x in cc:
    if x != processed[-1]:
        processed.append(x)

processed = processed[1:]
processed = {x: i for i, x in enumerate(processed)}

arr = [[0] * (n + 1) for _ in range(len(processed))]

for i, x in enumerate(c):
    arr[processed[x]][i + 1] += 1


for i in range(len(processed)):
    arr[i] = list(accumulate(arr[i]))

aT = list(zip(*arr))

for _ in range(q):
    l, r = map(int, input().split())
    right = aT[r]
    left = aT[l - 1]

    ans = 0
    for x, y in zip(left, right):
        if x < y:
            ans += 1
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
import copy

n, q = map(int, input().split())
c = list(map(int, input().split()))

# cとの0〜var - 1の変換表を作る
cc = copy.deepcopy(c)
cc.sort()
processed = [-1]

for x in cc:
    if x != processed[-1]:
        processed.append(x)

processed = processed[1:]
processed = {x: i for i, x in enumerate(processed)}

arr = [[0] * (n + 1) for _ in range(len(processed))]

for i, x in enumerate(c):
    arr[processed[x]][i + 1] += 1


arr = np.array(arr)
arr = arr.cumsum(axis=1)

for _ in range(q):
    l, r = map(int, input().split())
    tmp = arr[:, r] - arr[:, l - 1]
    print(np.where(tmp > 0)[0].shape[0])

Submission status: Time Limit Exceeded

Solution code:
# F - Range Set Query
import sys
from sys import exit
from collections import deque
from copy import deepcopy
from bisect import bisect_left, bisect_right, insort_left, insort_right
from heapq import heapify, heappop, heappush
from itertools import product, permutations, combinations, combinations_with_replacement
from functools import reduce
from math import gcd, sin, cos, tan, asin, acos, atan, degrees, radians

sys.setrecursionlimit(10**6)
INF = 10**20
eps = 1.0e-20
MOD = 10**9+7

def lcm(x,y):
    return x*y//gcd(x,y)
def lgcd(l):
    return reduce(gcd,l)
def llcm(l):
    return reduce(lcm,l)
def powmod(n,i,mod=MOD):
    return pow(n,mod-1+i,mod) if i<0 else pow(n,i,mod)
def div2(x):
    return x.bit_length()
def div10(x):
    return len(str(x))-(x==0)
def intput():
    return int(input())
def mint():
    return map(int,input().split())
def lint():
    return list(map(int,input().split()))
def ilint():
    return int(input()), list(map(int,input().split()))
def judge(x, l=['Yes', 'No']):
    print(l[0] if x else l[1])
def lprint(l, sep='\n'):
    for x in l:
        print(x, end=sep)
def ston(c, c0='a'):
    return ord(c)-ord(c0)
def ntos(x, c0='a'):
    return chr(x+ord(c0))
class counter(dict):
    def __init__(self, *args):
        super().__init__(args)
    def add(self,x,d=1):
        self.setdefault(x,0)
        self[x] += d
    def list(self):
        l = []
        for k in self:
            l.extend([k]*self[k])
        return l
class comb():
    def __init__(self, n, mod=None):
        self.l = [1]
        self.n = n
        self.mod = mod
    def get(self,k):
        l,n,mod = self.l, self.n, self.mod
        k = n-k if k>n//2 else k
        while len(l)<=k:
            i = len(l)
            l.append(l[i-1]*(n+1-i)//i if mod==None else (l[i-1]*(n+1-i)*powmod(i,-1,mod))%mod)
        return l[k]
def pf(x,mode='counter'):
    C = counter()
    p = 2
    while x>1:
        k = 0
        while x%p==0:
            x //= p
            k += 1
        if k>0:
            C.add(p,k)
        p = p+2-(p==2) if p*p<x else x
    if mode=='counter':
        return C
    S = set([1])
    for k in C:
        T = deepcopy(S)
        for x in T:
            for i in range(1,C[k]+1):
                S.add(x*(k**i))
    if mode=='set':
        return S
    if mode=='list':
        return sorted(list(S))

class SegmentTree():
    
    # 目的関数！！
    def func(self,x,y):
        return x+y
    
    # インデックスは0-start
    # 初期化（配列と初期値）
    def __init__(self, array, initial_value=0):
        
        self.n = len(array)
        self.init_val = initial_value
        self.num = 2**(self.n-1).bit_length()
        self.seg = [self.init_val]*2*self.num
        
        for i in range(self.n):
            self.seg[i+self.num-1] = array[i]
        for i in range(self.num-2,-1,-1):
            self.seg[i] = self.func(self.seg[2*i+1],self.seg[2*i+2]) 
    
    # k番目の要素をxに変更
    def update(self,k,x):
        k += self.num-1
        self.seg[k] = x
        while k:
            k = (k-1)//2
            self.seg[k] = self.func(self.seg[2*k+1],self.seg[2*k+2])
    
    # k番目の要素にxを追加
    def add(self,k,x):
        k_tmp = k+self.num-1
        x_tmp = self.seg[k_tmp]+x
        self.update(k,x_tmp)
    
    # [p,q]に対するクエリを処理
    def query(self,p,q):
        q += 1
        if q<=p:
            return self.init_val
        p += self.num-1
        q += self.num-2
        res = self.init_val
        while q-p>1:
            if p&1 == 0:
                res = self.func(res,self.seg[p])
            if q&1 == 1:
                res = self.func(res,self.seg[q])
                q -= 1
            p = p//2
            q = (q-1)//2
        if p == q:
            res = self.func(res,self.seg[p])
        else:
            res = self.func(self.func(res,self.seg[p]),self.seg[q])
        return res
    
    # もとの配列を出力
    def result(self):
        return self.seg[self.num-1:self.n+self.num-1]

class FenwickTree():
    
    # インデックスは1-start
    # 初期化
    def __init__(self, n):
        self.n = n
        self.data = [0]*(n+1)
        self.el = [0]*(n+1)
    
    # private function
    def summation(self, i):
        s = 0
        while i > 0:
            s += self.data[i]
            i -= i & -i
        return s
    
    # i番目の要素にxを加える（初期値 0）
    def add(self, i, x):
        self.el[i] += x
        while i <= self.n:
            self.data[i] += x
            i += i & -i
    
    # i番目の要素 or [i,j]の要素和を取得
    def get(self, i, j=None):
        if j is None:
            return self.el[i]
        return self.summation(j) - self.summation(i-1)

######################################################

N,Q=mint()
C=lint()
T=FenwickTree(N)
where=dict()
q=[]
for j in range(Q):
    l,r=mint()
    insort_left(q,(r,l,j))
ans=[0]*Q
i=1
for j in range(Q):
    while i<=q[j][0]:
        c=C[i-1]
        if c in where:
            T.add(where[c],-1)
        T.add(i,1)
        where[c]=i
        i+=1
    ans[q[j][2]]=T.get(q[j][1],q[j][0])
lprint(ans)