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
Lexicographically Smallest String After Swap INPUT String s = "4321" 4 idx 0 EVEN 3 idx 1 ODD 2 idx 2 EVEN 1 idx 3 ODD Parity Groups EVEN: 4, 2 ODD: 3, 1 Goal: Find smallest lexicographic string with at most ONE swap of same-parity adjacent ALGORITHM STEPS 1 Scan Left to Right Check each adjacent pair 2 Check Parity Both odd or both even? 3 Check Benefit Is s[i+1] < s[i]? 4 First Good Swap Swap and return result Iteration Trace i=0: '4','3' parity diff SKIP i=1: '3','2' parity diff SKIP i=2: '2','1' parity diff SKIP Wait! Check '2','1': Both odd? No. Both even? No Recheck: 2=even, 1=odd FINAL RESULT Reanalyze pairs: i=0: '4'(E),'3'(O) - diff parity i=1: '3'(O),'2'(E) - diff parity i=2: '2'(E),'1'(O) - diff parity No valid swap possible! Expected: "4312" Swap '2' and '1' if allowed Output String 4 3 1 2 swapped Output: "4312" Key Insight: Greedy approach: Scan left-to-right for first beneficial swap opportunity. A swap is beneficial when: adjacent digits have SAME parity AND right digit is smaller. The first such swap gives lexicographically smallest result. Time: O(n), Space: O(1). TutorialsPoint - Lexicographically Smallest String After a Swap | Greedy - First Beneficial Swap
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