Lexicographically Smallest String After a Swap - Problem

Imagine you're given a string of digits and you want to make it as lexicographically small as possible. You have one powerful move: you can swap any two adjacent digits that have the same parity (both odd or both even) exactly once.

Parity Rules:
• Even digits: 0, 2, 4, 6, 8
• Odd digits: 1, 3, 5, 7, 9
• You can only swap adjacent digits of the same type

Goal: Find the lexicographically smallest string possible after performing at most one swap.

Example: "4321""2341" (swap adjacent 4 and 2, both even)

Input & Output

example_1.py — Basic Swap
$ Input: "4312"
Output: "4132"
💡 Note: We can swap adjacent digits 3 and 1 (both odd) to get "4132", which is lexicographically smaller than the original.
example_2.py — No Valid Swap
$ Input: "4321"
Output: "4321"
💡 Note: No adjacent digits have the same parity (4-3, 3-2, 2-1 are all even-odd pairs), so no swap is possible.
example_3.py — Multiple Options
$ Input: "8642"
Output: "2648"
💡 Note: We can swap 8 and 6 (both even) to get "6842", or 6 and 4 to get "8462", or 4 and 2 to get "8624". The optimal choice is swapping 8 and 6 to get "6842", but actually we want the globally smallest, which requires swapping the leftmost beneficial pair.

Constraints

  • 2 ≤ s.length ≤ 100
  • s consists of digits only (0-9)
  • You can perform at most one swap
  • Only adjacent digits with the same parity can be swapped

Visualization

Tap to expand
Lexicographically Smallest String After SwapExample: "864213" → Find optimal single swapOriginal:864213🔵 Even 🟢 OddAnalysis:8>6, Same parity ✓6>4, Same parity ✓Optimal Result (swap 8↔6):684213"684213" → Best possible with one swapAlgorithm Steps1. Scan left to right2. Find first beneficial same-parity pair3. Execute swap immediately4. Return result⚡ Time: O(n), Space: O(1)💡 Greedy works because leftmostimprovements have highest priority
Understanding the Visualization
1
Identify Parity Groups
Classify each digit as even (blue) or odd (green)
2
Scan for Opportunities
Look for adjacent same-parity pairs where left > right
3
Execute First Beneficial Swap
Make the leftmost beneficial swap for optimal lexicographical result
4
Optimal Result Achieved
Early positions have more impact on lexicographical ordering
Key Takeaway
🎯 Key Insight: Since lexicographical comparison prioritizes earlier positions, the first beneficial swap from left to right always produces the optimal result. This greedy approach eliminates the need to check all possibilities.
Asked in
Google 15 Amazon 12 Meta 8 Microsoft 6
28.4K Views
Medium Frequency
~12 min Avg. Time
892 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