The problem
I have an array with N numbers. The numbers may be disctints and may also be unordered. I have to answer Q queries about how many distinct numbers there are between A and B. Where A, B are indices between 0 <= A <= B < array.Length.
I know how to do it O(N) per query by using a HashTable but I'm asking for a more efficient solution. I tried to improve it with sqrt decomposition and also with a segment tree but I couldn't. I'm not showing any code because I did not find any idea that worked. I'm looking for someone to give an explanation of a faster solution.
UPDATE
I read you can collect the queries and then answer them all by using a Binary Indexed Tree (BIT). Can someone explain how to do it. Assume I know how a BIT works.
For each index
i
find the previous indexprev[i]
that has the same value (or -1 if there's no such index). It may be done inO(n)
average by going left to right with hash_map, then the answer for range [l;r) of indices is number of elementsi
in range [l;r) such that their value is less thenl
(it require some thinking but should be clear)Now we will solve problem "given range
[l;r)
and valuec
find number of elements that are less thenc
" on arrayprev
. It may be done inO(log^2)
using segment tree, if we save in each vertex all the numbers that are in its range(subtree). (On each query we will getO(log n)
vertices and do binary search in them)