2434. Using a robot to print the lexicographically smallest string

Time Limit Exceeded

My solution is much more elegant, but i didn't notice, min(s) being done for each loop

    def robotWithString(self, s: str) -> str:
         p = ''
         t = []
         while s != '':
             minele = min(s)
             if t and t[-1] <= minele:
                 p += t.pop()
                 continue
             t += s[:s.index(minele)+1]
             p += t.pop()
             s = s[s.index(minele)+1:]
         while t:
             p += t.pop()
         return p

Best solution

    def robotWithString(self, s: str) -> str:
        min_char = min(s)
        min_char_count = s.count(min_char)
        res, stack, last_idx = "", [], len(s) - 1
        for idx, char in enumerate(s):
            if char == min_char:
                res += char
                min_char_count -= 1
                if min_char_count == 0:
                    if idx >= last_idx:
                        break
                    min_char = min(s[idx + 1:])
                    min_char_count = s[idx + 1:].count(min_char)
                    while stack and stack[-1] <= min_char:
                        res += stack.pop()
            else:
                stack.append(char)
  
        return res + "".join-1]