Problem Description
Given a string s containing only digits, return the lexicographically smallest string that can be obtained after swapping adjacent digits in s with the same parity at most once. Digits have the same parity if both are odd or both are even.
Key Insights
- The problem requires identifying adjacent digits with the same parity (odd or even).
- We can only perform one swap, so we need to choose wisely to ensure we get the smallest result.
- The lexicographical order means we want to arrange numbers in the smallest possible order.
Space and Time Complexity
Time Complexity: O(n), where n is the length of the string s, since we might need to traverse the string a couple of times.
Space Complexity: O(n), for storing the characters of the string in a list if needed.
Solution
To solve the problem, we can follow these steps:
- Traverse the string to identify adjacent digits with the same parity.
- For each identified pair, swap them and check if the resulting string is lexicographically smaller than the current smallest string.
- Keep track of the smallest string encountered during the swaps.
- Return the smallest string found.
We will primarily use a list to store the characters of the string for easy swapping and comparison.