Skip to content

Commit 2bfdefb

Browse files
committed
ID: 451 Sort Characters By Frequency (Hash Table)
1 parent 6f2cb27 commit 2bfdefb

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
'''
2+
Given a string, sort it in decreasing order based on the frequency of characters.
3+
4+
Input:
5+
"tree"
6+
Output:
7+
"eert"
8+
Explanation:
9+
'e' appears twice while 'r' and 't' both appear once.
10+
So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer.
11+
12+
Input:
13+
"cccaaa"
14+
Output:
15+
"cccaaa"
16+
17+
Input:
18+
"Aabb"
19+
Output:
20+
"bbAa"
21+
Explanation:
22+
"bbaA" is also a valid answer, but "Aabb" is incorrect.
23+
Note that 'A' and 'a' are treated as two different characters.
24+
'''
25+
26+
class Solution:
27+
''' Approach #1 (Hash Table) '''
28+
'''
29+
Count the frequency of each letter and then sort them according to frequency in decreasing order
30+
'''
31+
def frequencySort(self, s: str) -> str:
32+
# Dictionary to store Frequency
33+
Hash = dict()
34+
35+
for letter in s:
36+
if(letter in Hash):
37+
Hash[letter] += 1
38+
else:
39+
Hash[letter] = 1
40+
41+
# Hash.items() Return object of dict_items -> (key, value)
42+
itemList = list(Hash.items())
43+
# Sorting itemList according to frequency in decreasing order
44+
itemList.sort(key=lambda x:(x[1],x[0]), reverse=True)
45+
46+
string = ""
47+
for item in itemList:
48+
# Repeat letter frequency (item[1]) times
49+
string += item[0]*item[1]
50+
51+
return string
52+
53+
54+
if __name__ == '__main__':
55+
sol = Solution()
56+
s = "tree"
57+
print(sol.frequencySort(s))

0 commit comments

Comments
 (0)