Distinct values in a range

Time limit2sMemory limit512 MB

Summary
Given a static array and many range queries, report how many distinct values occur in each subarray.
Level

Medium7 of 10

Topics
Array, Sorting, Prefix sum, Binary search
Solved
No attempts yet

Problem

A sequence A1,A2,…,ANA_1, A_2, \dots, A_N of length NN is given. Write a program that answers MM queries on this sequence.

  • i j: report how many distinct numbers appear among Ai,Ai+1,…,AjA_i, A_{i+1}, \dots, A_j.

A value that appears several times inside the range counts once.

Input

The first line contains the size of the sequence, NN. (1≤N≤100,0001 \le N \le 100{,}000)

The second line contains A1,A2,…,ANA_1, A_2, \dots, A_N, separated by spaces. (1≤Ai≤1,000,0001 \le A_i \le 1{,}000{,}000)

The third line contains the number of queries, MM. (1≤M≤100,0001 \le M \le 100{,}000)

Each of the next MM lines holds one query as two integers ii and jj. (1≤i≤j≤N1 \le i \le j \le N)

Output

For each query, print the number of distinct values in the range [i,j][i, j] on its own line, in the order the queries are given.

Examples2

  1. Example 1

    Input
    5
    1 1 2 1 3
    3
    1 5
    2 4
    3 5
    
    Expected output
    3
    2
    3
    
  2. Example 2

    Input
    1
    1000000
    1
    1 1
    
    Expected output
    1