Lexicographically Smallest String After a Swap - Problem
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. For example, 5 and 9, as well as 2 and 4, have the same parity, while 6 and 9 do not.
Input & Output
Example 1 — Basic Swap
$
Input:
s = "4321"
›
Output:
"4312"
💡 Note:
We can swap 2 and 1 (both even) to get "4312", which is lexicographically smaller than the original
Example 2 — No Beneficial Swap
$
Input:
s = "1234"
›
Output:
"1234"
💡 Note:
Already in ascending order. Any adjacent same-parity swap would make it lexicographically larger
Example 3 — Multiple Options
$
Input:
s = "8742"
›
Output:
"8742"
💡 Note:
We can check adjacent pairs: 8 and 7 have different parity, 7 and 4 have different parity, 4 and 2 have same parity (both even). Swapping 4 and 2 gives "8724" which is lexicographically larger, so we don't perform the swap and return the original string.
Constraints
- 1 ≤ s.length ≤ 105
- s consists of digits only
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code