Maximum Frequency Stack LeetCode solution in Python

1
# Runtime: 347 ms (Top 94.76%) | Memory: 22.7 MB (Top 60.86%)
2
class FreqStack:
3

4
def __init__(self):
5
self.cnt = {}
6
self.maxcount = 0
7
self.stack = {}
8

9
def push(self, val: int) -> None:
10
count = self.cnt.get(val, 0) + 1
11
self.cnt[val] = count
12
if count > self.maxcount:
13
self.maxcount = count
14
self.stack[count] = []
15
self.stack[count].append(val)
16

17
def pop(self) -> int:
18
res = self.stack[self.maxcount].pop()
19
self.cnt[res] -= 1
20
if not self.stack[self.maxcount]:
21
self.maxcount -= 1
22
return res
23

24

25
# Your FreqStack object will be instantiated and called as such:
26
# obj = FreqStack()
27
# obj.push(val)
28
# param_2 = obj.pop()

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0