# 1 line Python code.

• ``````class Solution(object):
def frequencySort(self, str):
"""
:type str: str
:rtype: str
"""
return "".join([char * times for char, times in collections.Counter(str).most_common()])
``````

• AC now, seems test cases have been updated several minutes ago.

• By using heqpq.nlargest

``````    h = [(v,k) for k,v in Counter(s).items()]
return ''.join(v*k for v,k in heapq.nlargest(len(h),h))``````

• @realisking Could you explain the logic. I'm new to python

• @rajanpawar10
Check it here. Then make it 1 line using list comprehension.

• I reduce to the result. sort takes only O(1) here so it's okay.
Could be only 1 line, but too long.

``````def frequencySort(self, s):
c = collections.Counter(s)
return reduce(lambda a,b: b[1]*b[0]+a, sorted((c[i],i) for i in c), '')``````

• @lee215 said in 1 line Python code.:

I reduce to the result. sort takes only O(1) here so it's okay.

What do you mean by sort takes only O(1)?

• @realisking the length of list is at most 26*2. N is a constant.

• @lee215 Could you explain more clearly about why sort takes only O(1)?

• @xingjiu Complexity to sort a list of length 52 is O(1).

• @lee215 What kind of sort method you use? why it is O(1)?

• @xingjiu
When we talked about O(n), O(nlogn) or something like that in time complexity, typically we are talking about a large number. In this case, although sorting takes O(nlogn), since n == 52 which is a constant, it is also O(1).

• @realisking Thanks

• So brilliant!
I like the `Counter().most_common()`!

• `[...]` is redundant. You could do

``````return "".join(char * times for char, times in collections.Counter(str).most_common())`
``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.