Skip to main content

3216. Lexicographically Smallest String After a Swap

Hint

class Solution {
public:
string getSmallestString(string s)
{
// Iterate through the string from the beginning to the second last character
for ()
{
// Check if both current and next characters have the same parity (both even or both odd)
// and if the current character is greater than the next character
if ()
{
// Swap the current character with the next one
// Exit the loop after the first swap
}
}
// Return the modified string
}
};

class Solution {
public:
string getSmallestString(string s)
{
for (int i = 0; i < s.size() - 1; ++i)
{
if (s[i] % 2 == s[i + 1] % 2 && s[i] > s[i + 1])
{
swap(s[i], s[i + 1]); break;
}
}
return s;
}
};
  • T: O(n)O(n)
  • S: O(1)O(1)