-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
frequency-tracker.py
47 lines (40 loc) · 1.2 KB
/
frequency-tracker.py
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
39
40
41
42
43
44
45
46
47
# Time: ctor: O(1)
# add: O(1)
# deleteOne: O(1)
# hasFrequency: O(1)
# Space: O(min(n, r))
# freq table
class FrequencyTracker(object):
def __init__(self):
self.__cnt = collections.Counter()
self.__freq = collections.Counter()
def add(self, number):
"""
:type number: int
:rtype: None
"""
self.__freq[self.__cnt[number]] -= 1
if self.__freq[self.__cnt[number]] == 0:
del self.__freq[self.__cnt[number]]
self.__cnt[number] += 1
self.__freq[self.__cnt[number]] += 1
def deleteOne(self, number):
"""
:type number: int
:rtype: None
"""
if self.__cnt[number] == 0:
return
self.__freq[self.__cnt[number]] -= 1
if self.__freq[self.__cnt[number]] == 0:
del self.__freq[self.__cnt[number]]
self.__cnt[number] -= 1
self.__freq[self.__cnt[number]] += 1
if self.__cnt[number] == 0:
del self.__cnt[number]
def hasFrequency(self, frequency):
"""
:type frequency: int
:rtype: bool
"""
return frequency in self.__freq