Problem Description
Given a string s composed only of digits, you are allowed to perform at most one swap between any two adjacent digits if they have the same parity (both digits are even or both are odd). The goal is to obtain the lexicographically smallest string possible.
Key Insights
- Only adjacent swaps are allowed.
- The swap can only be done if both digits share the same parity.
- You can perform at most one swap.
- Check every possible valid adjacent swap and choose the one that produces the smallest string.
- If no swap improves the string, return the original string.
Space and Time Complexity
Time Complexity: O(n^2), where n is the length of the string (each swap operation involves copying the string for comparison). Space Complexity: O(n) for storing candidate strings.
Solution
The approach involves iterating through the string and checking each pair of adjacent digits to see if they have the same parity. For every valid pair:
- Create a new candidate string by swapping the two digits.
- Compare the candidate with the current best result.
- Keep track of the lexicographically smallest string. If no swap yields improvement, return the original string.
Data structures used include basic string manipulation functions and arrays (or lists) for converting strings when needed. The algorithm is essentially greedy, as it evaluates all one-time swap possibilities and picks the optimal result.