0

Suppose, I've an array [1, 2, 3, 5, 5, 6, 5, 5]

Now, there can be two kind of operation. One of them is "update" operation , that is increase the value in index 4[1 based indexing] by X. Other operation is "query" operation, where given a range, suppose [4, 8](both inclusive) and a value suppose 5. Now find the frequency of the value 5 in the given range [4, 8]. In this case, the answer should be 4.

How can I do this "query" step using segment tree??

Thanks in advance.

Anik Roy
  • 15
  • 5

1 Answers1

0

I have two solutions but without using segment tree

First Solution :

  • Split each query into freq(r,x)-freq(l-1,x)

  • Iterate over the input and store the counts in an array (or map if
    the range is big)

  • If there is a query on your position, add/subtract the count from the array This should work in O(n + q) if the elements are small enough
    for array or O(n + q log n) if you need to use map.

Second Solution : use Mo's Algorithm for solving this problem with Time complexity O((N + Q) * sqrt(N) * F).

Ahmed Gamal
  • 1,666
  • 1
  • 17
  • 25