TLE

class Solution:
    def sortString(self, s: str) -> str:
        """
        tc O(N) sc O(N)
        1. cnt ocurrance for each c in s 
        2. a-z  append to res and z-a append to res 
        3. keep doing step2 until res reaches len of s 
        """
        d = {}
        for c in s:
            key = ord(c) - ord('a')
            if key not in d:
                d[key] = 0
            d[key] += 1
        res = []
        while res != len(s):
            for k in range(1,27):
                if k in d and d[k] > 0:
                    c = chr(ord('a') + k)
                    res.append(c)
                    d[k] -= 1
            for k2 in range(26,-1,-1):
                if k2 in d and d[k2] > 0:
                    c = chr(ord('a') + k2)
                    res.append(c)
                    d[k2] -= 1
        return ''.join(res)


use Counter instead

class Solution:
    def sortString(self, s: str) -> str:
        """
        tc O(N) sc O(N)
        1. cnt ocurrance for each c in s 
        2. a-z  append to res and z-a append to res 
        3. keep doing step2 until res reaches len of s 
        """
        d = Counter(s)
            
        res = []
        flag = True 
        
        while len(res) < len(s):
            for c in sorted(d)if flag else sorted(d,reverse = True) :
                res.append(c)
                d[c] -=1 
                if d[c] == 0:
                    d.pop(c) # del d[c]
            flag = not flag 
            
        return ''.join(res)