Here's a solution that doesn't require segment tree.
Preprocessing:
- For each number
arr[i]
, push i to the 2D vector(or ArrayList) with indexarr[i]
.
Answering Queries:
For any query do a binary search on vector[num] to find the index of the maximum index of num in that vector that's less than or equal to right range, let's call it R. Then find the minimum index that's greater than or equal to left range, let's call it L. Print R - L + 1
Runtime: Preprocessing in O(1) per item, taking total O(N) time. Per Query answer: O(lg(N))
Space: Quite linear assuming vector or ArrayList