LeetCode solutions

1472. Increasing Decreasing String

My accepted Python solution to LeetCode problem 1472, Increasing Decreasing String, running in 26ms.

  • Difficulty: Easy
  • Python
  • Runtime 26ms
  • Memory 17.4MB

Read the problem on LeetCode View on GitHub

Python

Accepted on LeetCode — runtime 26ms, memory 17.4MB, accepted 2025-12-30.

python
class Solution:
    def sortString(self, s: str) -> str:
        from collections import Counter
        count = Counter(s)
        result = []
        
        while len(result) < len(s):
            # Step 1-3: Pick smallest to largest
            for c in sorted(count.keys()):
                if count[c] > 0:
                    result.append(c)
                    count[c] -= 1
            
            # Step 4-6: Pick largest to smallest
            for c in sorted(count.keys(), reverse=True):
                if count[c] > 0:
                    result.append(c)
                    count[c] -= 1
        
        return ''.join(result)

Source