Skip to content

Commit 81f5165

Browse files
authored
Create range-frequency-queries.cpp
1 parent c20a436 commit 81f5165

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

C++/range-frequency-queries.cpp

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
// Time: ctor: O(n)
2+
// query: O(logn)
3+
// Space: O(n)
4+
5+
class RangeFreqQuery {
6+
public:
7+
RangeFreqQuery(vector<int>& arr) {
8+
for (int i = 0; i < size(arr); ++i) {
9+
idxs_[arr[i]].emplace_back(i);
10+
}
11+
}
12+
13+
int query(int left, int right, int value) {
14+
const auto& arr = idxs_[value];
15+
return upper_bound(cbegin(arr), cend(arr), right) -
16+
lower_bound(cbegin(arr), cend(arr), left);
17+
}
18+
19+
private:
20+
unordered_map<int, vector<int>> idxs_;
21+
};

0 commit comments

Comments
 (0)