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: "2748"
💡 Note: Can swap 8 and 7 (no - different parity), 7 and 4 (no - different parity), or 4 and 2 (yes - both even). Best result is swapping 8 and 4 for "4782", but we can only swap adjacent digits, so we get "8724". Actually, we can swap 4 and 2 to get "8742" → "8724". Wait, let me recalculate: 8 (even) can't swap with 7 (odd), 7 (odd) can't swap with 4 (even), 4 (even) can swap with 2 (even) giving "8724". But this makes it larger. So result is "8742".

Constraints

  • 1 ≤ s.length ≤ 105
  • s consists of digits only

Visualization

Tap to expand
Lexicographically Smallest String After Adjacent Same-Parity SwapInput: "4321"4321evenoddeveneven✓ Same parity swap: 2 ↔ 1Output: "4312"4312Lexicographically: "4312" < "4321"
Understanding the Visualization
1
Input
String of digits with potential same-parity adjacent pairs
2
Find Swap
Locate first beneficial adjacent same-parity swap
3
Result
Lexicographically smallest string after at most one swap
Key Takeaway
🎯 Key Insight: Since we can only swap once, the first beneficial adjacent same-parity swap gives the optimal result
Asked in
Google 25 Microsoft 18 Amazon 15
25.0K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen