-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0895-maximum-frequency-stack.js
More file actions
38 lines (31 loc) · 1.13 KB
/
0895-maximum-frequency-stack.js
File metadata and controls
38 lines (31 loc) · 1.13 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
/**
* Maximum Frequency Stack
* Time Complexity: O(1)
* Space Complexity: O(N)
*/
var FreqStack = function () {
this.elementCounts = new Map();
this.frequencyStacks = new Map();
this.currentMaxCount = 0;
};
FreqStack.prototype.push = function (val) {
let previousCountForVal = this.elementCounts.get(val) || 0;
let updatedCountForVal = previousCountForVal + 1;
this.elementCounts.set(val, updatedCountForVal);
this.currentMaxCount = Math.max(this.currentMaxCount, updatedCountForVal);
let targetStack = this.frequencyStacks.get(updatedCountForVal);
if (targetStack === undefined) {
targetStack = [];
this.frequencyStacks.set(updatedCountForVal, targetStack);
}
targetStack.push(val);
};
FreqStack.prototype.pop = function () {
const currentMaxFreqGroup = this.frequencyStacks.get(this.currentMaxCount);
const resultVal = currentMaxFreqGroup.pop();
this.elementCounts.set(resultVal, this.currentMaxCount - 1);
const remainingElementsInGroup = currentMaxFreqGroup.length;
remainingElementsInGroup === 0 &&
(this.frequencyStacks.delete(this.currentMaxCount), this.currentMaxCount--);
return resultVal;
};