Maximum Frequency Stack LeetCode solution in JavaScript

1
var FreqStack = function () {
2
//hashMap to keep track of the values being repeated
3
this.frequencyMap = {};
4

5
//List map to keep track of the sequence of the value being entered
6
this.listMap = {};
7

8
//Max Frequency variable to keep track of the max frequency
9
this.maxValueFrequency = 0;
10
};
11

12
/**
13
* @param {number} val
14
* @return {void}
15
*/
16
FreqStack.prototype.push = function (val) {
17
//if the hashMap doesn't have value being pushed then make a entry to it with 1 else increament by 1
18
this.frequencyMap[val] = this.frequencyMap[val]
19
? this.frequencyMap[val] + 1
20
: 1;
21

22
//get the frequency of the value being pushed
23
const currentValueFrequency = this.frequencyMap[val];
24

25
//check if the current frequency is max or itself
26
this.maxValueFrequency = Math.max(
27
this.maxValueFrequency,
28
currentValueFrequency
29
);
30

31
//if current value frequency is not in the listmap then make a new entry else push it
32
if (!this.listMap[currentValueFrequency])
33
this.listMap[currentValueFrequency] = [val];
34
else this.listMap[currentValueFrequency].push(val);
35
};
36

37
/**
38
* @return {number}
39
*/
40
FreqStack.prototype.pop = function () {
41
//make a temporary list of the max value frequency
42
const tempList = this.listMap[this.maxValueFrequency];
43

44
//get the last element from the temporary list
45
const top = tempList[tempList.length - 1];
46

47
//remove the item from the list
48
tempList.pop();
49

50
//update the list
51
this.listMap[this.maxValueFrequency] = tempList;
52

53
//if the popped item exist in the frequecy map then decrease it by 1
54
if (this.frequencyMap[top]) this.frequencyMap[top]--;
55

56
//if the max value frequency in the listmap is blank then reduce the maxValueFrequency;
57
if (this.listMap[this.maxValueFrequency].length === 0)
58
this.maxValueFrequency--;
59

60
//return the max value frequency with proper order if it is same
61
return top;
62
};
63

64
//Time O(Log n) // for both Push and Pop
65
//Space O(n) for storing all the values in the hashMap and listMap

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0