3216. Lexicographically Smallest String After a Swap¶
Intuition¶
To find the lexicographically smallest string by swapping adjacent digits with the same parity, we need to identify the first opportunity where a swap will result in a smaller string. This approach ensures that we achieve the smallest possible lexicographical order with a single swap.
Approach¶
Explanation:¶
- Initialization:
- Iterate through the string
sstarting from the second character (index 1) to the end. - Checking adjacent digits:
- For each character
s[i], check if it has the same parity as the previous characters[i-1].- Digits have the same parity if both are even or both are odd. This is determined using the modulus operator (
% 2).
- Digits have the same parity if both are even or both are odd. This is determined using the modulus operator (
- If
s[i-1]is greater thans[i]and both have the same parity, swapping them will result in a smaller string.- Perform the swap.
- Break out of the loop since only one swap is allowed.
- Return the modified string:
- Return the modified string
safter the swap.
Complexity¶
- Time complexity: O(n), where
nis the length of the string. - Space complexity: O(1), as we are modifying the string in place and using only a constant amount of extra space.