2025-08-22 18:29:25 +0000 UTC

Lexicographically Smallest String After a Swap

Code

class Solution:
    def getSmallestString(self, s: str) -> str:
        res = list(s)
        for i in range(len(s) - 1):
            cur, nxt = int(s[i]), int(s[i + 1])
            if cur % 2 == nxt % 2 and cur > nxt:
                res[i], res[i + 1] = s[i + 1], s[i]
                break        
        return "".join(res)