1
+ // Runtime: 672 ms (Top 16.08%) | Memory: 83 MB (Top 51.75%)
1
2
var FreqStack = function ( ) {
2
3
//hashMap to keep track of the values being repeated
3
4
this . frequencyMap = { } ;
4
-
5
+
5
6
//List map to keep track of the sequence of the value being entered
6
7
this . listMap = { } ;
7
-
8
+
8
9
//Max Frequency variable to keep track of the max frequency
9
10
this . maxValueFrequency = 0 ;
10
11
} ;
11
12
12
- /**
13
+ /**
13
14
* @param {number } val
14
15
* @return {void }
15
16
*/
16
17
FreqStack . prototype . push = function ( val ) {
17
18
//if the hashMap doesn't have value being pushed then make a entry to it with 1 else increament by 1
18
19
this . frequencyMap [ val ] = this . frequencyMap [ val ] ? this . frequencyMap [ val ] + 1 : 1 ;
19
-
20
+
20
21
//get the frequency of the value being pushed
21
22
const currentValueFrequency = this . frequencyMap [ val ] ;
22
-
23
+
23
24
//check if the current frequency is max or itself
24
25
this . maxValueFrequency = Math . max ( this . maxValueFrequency , currentValueFrequency ) ;
25
-
26
+
26
27
//if current value frequency is not in the listmap then make a new entry else push it
27
28
if ( ! this . listMap [ currentValueFrequency ] ) this . listMap [ currentValueFrequency ] = [ val ] ;
28
29
else this . listMap [ currentValueFrequency ] . push ( val ) ;
29
-
30
+
30
31
} ;
31
32
32
33
/**
@@ -35,26 +36,26 @@ FreqStack.prototype.push = function(val) {
35
36
FreqStack . prototype . pop = function ( ) {
36
37
//make a temporary list of the max value frequency
37
38
const tempList = this . listMap [ this . maxValueFrequency ] ;
38
-
39
- //get the last element from the temporary list
39
+
40
+ //get the last element from the temporary list
40
41
const top = tempList [ tempList . length - 1 ] ;
41
-
42
+
42
43
//remove the item from the list
43
44
tempList . pop ( ) ;
44
-
45
+
45
46
//update the list
46
47
this . listMap [ this . maxValueFrequency ] = tempList ;
47
-
48
+
48
49
//if the popped item exist in the frequecy map then decrease it by 1
49
50
if ( this . frequencyMap [ top ] ) this . frequencyMap [ top ] -- ;
50
-
51
+
51
52
//if the max value frequency in the listmap is blank then reduce the maxValueFrequency;
52
53
if ( this . listMap [ this . maxValueFrequency ] . length === 0 ) this . maxValueFrequency -- ;
53
-
54
+
54
55
//return the max value frequency with proper order if it is same
55
56
return top ;
56
-
57
+
57
58
} ;
58
59
59
60
//Time O(Log n) // for both Push and Pop
60
- //Space O(n) for storing all the values in the hashMap and listMap
61
+ //Space O(n) for storing all the values in the hashMap and listMap
0 commit comments