Skip to content

Commit dc3b850

Browse files
author
Gonzalo Diaz
committed
[BUGFIX] [Hacker Rank] Interview Preparation Kit: Dictionaries and Hashmaps: Frequency Queries. Solved ✅. Solve all test cases. High complexity
1 parent 5ae9145 commit dc3b850

File tree

1 file changed

+29
-40
lines changed

1 file changed

+29
-40
lines changed

src/hackerrank/interview_preparation_kit/dictionaries_and_hashmaps/frequency_queries.js

Lines changed: 29 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -19,54 +19,23 @@ export function freqQuery(queries) {
1919
const [operation, data] = query;
2020

2121
const currentFreqValue = dataMap?.[data] ?? __INITIAL__;
22+
let newFreqKey = currentFreqValue + 1;
2223

2324
switch (operation) {
2425
case __INSERT__:
25-
{
26-
// map of values
27-
dataMap[data] = currentFreqValue + 1;
26+
// map of values
27+
dataMap[data] = currentFreqValue + 1;
2828

29-
// map of frequencies
30-
const newFreqKey = currentFreqValue + 1;
31-
if (freqMap?.[newFreqKey]) {
32-
freqMap[newFreqKey].push(data);
33-
} else {
34-
freqMap[newFreqKey] = [data];
35-
}
36-
37-
if (freqMap?.[currentFreqValue]) {
38-
freqMap[currentFreqValue] = freqMap[currentFreqValue].filter(
39-
(f) => f !== data
40-
);
41-
}
42-
}
29+
// map of frequencies
30+
newFreqKey = currentFreqValue + 1;
4331
break;
4432
case __DELETE__:
45-
{
46-
// map of values
47-
dataMap[data] = Math.max(0, currentFreqValue - 1);
48-
49-
// map of frequencies
50-
const newFreqKey = currentFreqValue - 1;
51-
52-
if (newFreqKey > 0) {
53-
if (freqMap?.[newFreqKey]) {
54-
freqMap[newFreqKey].push(data);
55-
} else {
56-
freqMap[newFreqKey] = [data];
57-
}
58-
}
33+
// map of values
34+
dataMap[data] = Math.max(0, currentFreqValue - 1);
5935

60-
if (freqMap?.[currentFreqValue]) {
61-
freqMap[currentFreqValue] = freqMap[currentFreqValue].filter(
62-
(f) => f !== data
63-
);
36+
// map of frequencies
37+
newFreqKey = currentFreqValue - 1;
6438

65-
if (freqMap[currentFreqValue].length === 0) {
66-
delete freqMap?.[currentFreqValue];
67-
}
68-
}
69-
}
7039
break;
7140
case __SELECT__: {
7241
if (freqMap?.[data]) {
@@ -79,6 +48,26 @@ export function freqQuery(queries) {
7948
default:
8049
throw new Error('Invalid operation');
8150
}
51+
52+
if (operation === __INSERT__ || operation === __DELETE__) {
53+
if (newFreqKey > 0) {
54+
if (freqMap?.[newFreqKey]) {
55+
freqMap[newFreqKey].push(data);
56+
} else {
57+
freqMap[newFreqKey] = [data];
58+
}
59+
}
60+
61+
if (freqMap?.[currentFreqValue]) {
62+
freqMap[currentFreqValue] = freqMap[currentFreqValue].filter(
63+
(f) => f !== data
64+
);
65+
66+
if (freqMap[currentFreqValue].length === 0) {
67+
delete freqMap?.[currentFreqValue];
68+
}
69+
}
70+
}
8271
});
8372

8473
return result;

0 commit comments

Comments
 (0)