I wrote a solution to the leetcode problem Sort characters by frequency and the solution passes 34/35 test cases. On the last test case, there is a "time limit exceeded" error with an input string of 100000+ "a" and "b" characters. How can the following code be optimized to handle an input of that size?
def frequencySort(s):
"""
:type s: str
:rtype: str
"""
freq = {}
for i in s:
if i in freq:
freq[i] +=1
else:
freq[i] = 1
output = ""
newDict = sorted(freq.items(), key=lambda kv: kv[1],reverse = True)
for k,v in newDict:
for i in range(v):
output += k
return output
output += k
--- this rebuilds the string for each additional character as strings are immutable in Python (see Shlemiel the painter's algorithm). You're better off using''.join(chars)
, wherechars
is a list or generator. \$\endgroup\$