767. Reorganize String

Question

CleanShot 2024-09-21 at 19.47.17.png

Code

class Solution:
    def reorganizeString(self, s: str) -> str:
        
        hash_table = defaultdict(int)

        max_freq = 0
        letter = ''

        for i in range(len(s)):
            hash_table[s[i]] += 1

            if hash_table[s[i]] > max_freq:
                max_freq = hash_table[s[i]]
                letter = s[i]

        if max_freq > (len(s) + 1) // 2:
            return ""

        index = 0
        answer = [''] * len(s)
        while hash_table[letter] != 0:
            answer[index] = letter
            hash_table[letter] -= 1
            index += 2

        for char, count in hash_table.items():
            while count > 0:
                if index >= len(s):
                    index = 1
                answer[index] = char
                count -= 1
                index += 2

        return ''.join(answer)