Leetcode 2697. Lexicographically Smallest Palindrome
Given a string s
of length n
consisting of only lowercase English letters, convert it into a palindrome by changing some (possibly zero) characters such that the resulting palindrome is lexicographically smallest among all possible palindromes you can obtain in this way.
s
?
s
be an empty string?
s
to be a palindrome, s[i]
must equal s[n-1-i]
.s[i]
and s[n-1-i]
), change them to the smallest possible character if they do not match.left
at 0 and right
at n-1
.s[left]
!= s[right]
, set both to the minimum of the two.s[left]
and s[right]
.Here is the C++ code to accomplish the task:
#include <iostream>
#include <string>
std::string makeSmallestPalindrome(std::string s) {
int n = s.length();
int left = 0, right = n - 1;
while (left < right) {
if (s[left] != s[right]) {
char minChar = std::min(s[left], s[right]);
s[left] = s[right] = minChar;
}
left++;
right--;
}
return s;
}
int main() {
std::string s = "egcfe"; // Example input
std::string result = makeSmallestPalindrome(s);
std::cout << "Lexicographically smallest palindrome: " << result << std::endl;
return 0;
}
O(n): We iterate through the string with two pointers, each making at most n/2
steps. Therefore, the time complexity is linear with respect to the length of the string.
Space Complexity:
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?