-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsolution.js
More file actions
71 lines (53 loc) · 1.3 KB
/
Copy pathsolution.js
File metadata and controls
71 lines (53 loc) · 1.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/**
* @param {number[]} arr
* @param {number[][]} queries
* @returns {number[]}
*/
class Solution {
// First index >= target
lowerBound(arr, target) {
let low = 0;
let high = arr.length;
while (low < high) {
let mid = Math.floor((low + high) / 2);
if (arr[mid] < target) low = mid + 1;
else high = mid;
}
return low;
}
// First index > target
upperBound(arr, target) {
let low = 0;
let high = arr.length;
while (low < high) {
let mid = Math.floor((low + high) / 2);
if (arr[mid] <= target) low = mid + 1;
else high = mid;
}
return low;
}
freqInRange(arr, queries) {
// Map value -> occurrence positions
const mp = new Map();
for (let i = 0; i < arr.length; i++) {
if (!mp.has(arr[i])) {
mp.set(arr[i], []);
}
mp.get(arr[i]).push(i);
}
const ans = [];
for (const q of queries) {
const [l, r, x] = q;
// Value not present
if (!mp.has(x)) {
ans.push(0);
continue;
}
const positions = mp.get(x);
const left = this.lowerBound(positions, l);
const right = this.upperBound(positions, r);
ans.push(right - left);
}
return ans;
}
}