forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathremove-letter-to-equalize-frequency.py
More file actions
44 lines (37 loc) · 1.01 KB
/
remove-letter-to-equalize-frequency.py
File metadata and controls
44 lines (37 loc) · 1.01 KB
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
# Time: O(n)
# Space: O(1)
import collections
# freq table, edge cases
class Solution(object):
def equalFrequency(self, word):
"""
:type word: str
:rtype: bool
"""
cnt = collections.Counter(collections.Counter(word).itervalues())
if len(cnt) > 2:
return False
if len(cnt) == 1:
a = cnt.keys()[0]
return a == 1 or cnt[a] == 1
a, b = cnt.keys()
if a > b:
a, b = b, a
return (a == 1 and cnt[a] == 1) or (a+1 == b and cnt[b] == 1)
# Time: O(26 * n)
# Space: O(1)
import collections
# brute force, freq table
class Solution2(object):
def equalFrequency(self, word):
"""
:type word: str
:rtype: bool
"""
cnt = collections.Counter(collections.Counter(word))
for c in word:
cnt[c] -= 1
if len(collections.Counter(c for c in cnt.itervalues() if c)) == 1:
return True
cnt[c] += 1
return False