Python Counter most_common trick

  • 1

    Python Counter has a function most_common() that does exactly what is asked:
    Return a list of the n most common elements and their counts from the most common to the least. If n is omitted or None, most_common() returns all elements in the counter. Elements with equal counts are ordered arbitrarily

    def frequencySort(s):
        s = Counter(s).most_common()
        result = ""
        for i in s:
            result += i[0]*i[1]
        return result

Log in to reply

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