Lexicographically Smallest String After a Swap Problem
Description
LeetCode Problem 3216.
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 <= 100sconsists only of digits.
Solution
Approach: Greedy
Only one swap is allowed, and it must exchange two adjacent digits of the same parity. Scan the string from left to right and swap the first adjacent pair where the digits have the same parity and the left one is larger; that makes the string smaller at the earliest possible position, so it is the best swap. If there is no such pair, the string is already the smallest and is returned as is.
Complexity: time O(n), space O(n), where n is the length of s.
class Solution:
def getSmallestString(self, s: str) -> str:
for i in range(len(s) - 1):
a, b = ord(s[i]), ord(s[i + 1])
if (a + b) % 2 == 0 and a > b:
return s[:i] + s[i + 1] + s[i] + s[i + 2 :]
return s