Sort Characters By Frequency - Python Leetcode Solution

 Given a string, sort it in decreasing order based on the frequency of characters.

Example 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.

Example 2:

Input:
"cccaaa"

Output:
"cccaaa"

Explanation:
Both 'c' and 'a' appear three times, so "aaaccc" is also a valid answer.
Note that "cacaca" is incorrect, as the same characters must be together.

Example 3:

Input:
"Aabb"

Output:
"bbAa"

Explanation:
"bbaA" is also a valid answer, but "Aabb" is incorrect.
Note that 'A' and 'a' are treated as two different characters.
class Solution:
    def frequencySort(self, s: str) -> str:   
        counts = collections.Counter(s)
        print(counts)
        pq = []
        for t,freq in counts.items():
            heapq.heappush(pq,(-1*freq,t))
        string_builder = []
        while pq:
            freq,t = heapq.heappop(pq)
            string_builder.append(-1* freq * t)
        return ''.join(string_builder)
TC: O(nlogn) SC: O(n)
class Solution:
    def frequencySort(self, s: str) -> str:   
        if not s:
            return ""
        counts = collections.Counter(s)
        maxf = max(counts.values())
        buckets = [[] for _ in range(maxf+1)]
        for c,freq in counts.items():
            buckets[freq].append(c)
            
        string_builder = []
        for i in range(len(buckets)-1,0,-1):
            for c in buckets[i]:
                string_builder.append(c*i)
        return "".join(string_builder)
O(N) O(N)

No comments:

Post a Comment

Featured Post

H1B Visa Stamping at US Consulate

  H1B Visa Stamping at US Consulate If you are outside of the US, you need to apply for US Visa at a US Consulate or a US Embassy and get H1...