Ctrl K

Swap Neighbors of the Same Parity

Easy
You are given a string digits of decimal digits. At most once, you may swap two adjacent digits, but only if both are even or both are odd (for example, 3 and 7 or 0 and 8 qualify, while 4 and 5 do not). Return the lexicographically smallest string you can get this way. Making no swap at all is allowed.
Example 1
digits="6285" → '2685'

6 and 2 are both even, so they may be swapped, and "2685" is smaller than the original.

Example 2
digits="7429" → '7249'

The pairs 7/4 and 2/9 mix parities. 4 and 2 are both even, and swapping them gives the smaller "7249".

Example 3
digits="1357" → '1357'

All digits are odd, but they already increase, so any swap would only make the string larger.

Constraints
  • 2 ≤ len(digits) ≤ 100
  • digits consists of digits only
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsPalindrome From Letter Tiles EasyPalindrome With One Eraser Stroke EasyRise and Fall Lineup EasyMost Even L/R Pieces EasyTime Behind the Smudges Easy
loading Python…
Input
digits="6285"
Expected
'2685'

Run checks the first 3 tests in your browser. Submit checks all 127 tests on the server, hidden ones included.