1

Input: "tree"

Output: "eert"

Explanation: 'e' appears twice while 'r' and 't' both appear once. So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer.

I tried something like this :

class Solution(object):
def frequencySort(self, s):
    """
    :type s: str
    :rtype: str
    """
    has = dict()
    l = list()
    for c in s:
        if c not in has:
            has[c] = 1
        else:
            has[c] += 1
    for k in sorted(has,key = has.get, reverse = True):
        for i in range(has[k]):
            l.extend(k)
    return ("".join(l))

but its O(n * m) n = length of string, m = maximum occurrence of a character

How can i improve this to order of n?

Hith
  • 308
  • 1
  • 6
  • 16

1 Answers1

2

Is there a reason you cannot use the built in sort with a lambda key?

>>> a = 'aabbbcccccd'
>>> sorted(a, key=lambda c: a.count(c))
['d', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c', 'c', 'c']
>>> sorted(a, key=lambda c: a.count(c), reverse=True)
['c', 'c', 'c', 'c', 'c', 'b', 'b', 'b', 'a', 'a', 'd']
>>> ''.join(sorted(a, key=lambda c: a.count(c), reverse=True))
'cccccbbbaad'

I believe python's sort methods is O(n log n), but the count will make this O(n^2)

Easton Bornemeier
  • 1,918
  • 8
  • 22