-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathfrequency-queries.js
45 lines (38 loc) · 966 Bytes
/
frequency-queries.js
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
/*
Title: Frequency Queries
Difficulty: Medium
Score: 40
Link: https://www.hackerrank.com/challenges/frequency-queries/
*/
function freqQuery(arr) {
const result = [];
const hash = {};
const freq = [];
for (let i = 0; i < arr.length; i += 1) {
const [action, value] = arr[i];
const initValue = hash[value] || 0;
if (action === 1) {
hash[value] = initValue + 1;
freq[initValue] = (freq[initValue] || 0) - 1;
freq[initValue + 1] = (freq[initValue + 1] || 0) + 1;
}
if (action === 2 && initValue > 0) {
hash[value] = initValue - 1;
freq[initValue - 1] += 1;
freq[initValue] -= 1;
}
if (action === 3) result.push(freq[value] > 0 ? 1 : 0);
}
return result;
}
let input = [
[1, 5],
[1, 6],
[3, 2],
[1, 10],
[1, 10],
[1, 6],
[2, 5],
[3, 2]
];
console.log(freqQuery(input));