-
-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy path0895-maximum-frequency-stack.py
More file actions
38 lines (31 loc) · 870 Bytes
/
0895-maximum-frequency-stack.py
File metadata and controls
38 lines (31 loc) · 870 Bytes
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
# time complexity: O(1)
# space complexity: O(n)
from collections import defaultdict
class FreqStack:
def __init__(self):
self.freq = defaultdict(int)
self.groups = defaultdict(list)
self.maxFreq = 0
def push(self, val: int) -> None:
self.freq[val] += 1
currFreq = self.freq[val]
if currFreq > self.maxFreq:
self.maxFreq = currFreq
self.groups[currFreq].append(val)
def pop(self) -> int:
first = self.groups[self.maxFreq].pop()
self.freq[first] -= 1
if not self.groups[self.maxFreq]:
self.maxFreq -= 1
return first
freqStack = FreqStack()
freqStack.push(5)
freqStack.push(7)
freqStack.push(5)
freqStack.push(7)
freqStack.push(4)
freqStack.push(5)
print(freqStack.pop())
print(freqStack.pop())
print(freqStack.pop())
print(freqStack.pop())