Talentd
FleetCode

3216. Lexicographically Smallest String After a Swap

Easy54.6% acceptance1 company

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.

Example 1:

Input: s = "45320"

Output: "43520"

Explanation:

s[1] == '5' and s[2] == '3' both have the same parity, and swapping them results in the lexicographically smallest string.

Example 2:

Input: s = "001"

Output: "001"

Explanation:

There is no need to perform a swap because s is already the lexicographically smallest.

Constraints:

  • 2 <= s.length <= 100
  • s consists only of digits.

Asked at 1 company

Hints open one at a time

Hint 1
Try all possible swaps satisfying the constraints and find the one that results in the lexicographically smallest string.
5:09
Still stuck?Read 3 approaches, or watch a walkthrough.
Open solution
Loading editor…
1class Solution:
2 def getSmallestString(self, s: str) -> str:
3
Starter codePython 3Spaces: 4
Examples
Input
"45320"
Input
"001"
Your code is saved on this device.Solution