LeetCode 2663: Lexicographically Smallest Beautiful String Solution
Master LeetCode problem 2663 (Lexicographically Smallest Beautiful String), a hard challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
Problem Explanation
Explanation
To find the lexicographically smallest beautiful string larger than the given string s, we can follow these steps:
- Iterate through the string
sfrom right to left to find the first positioniwhere we can increase the character at this position. - If we find such a position, increment the character at that position to the next possible character in the range
[1, k]that does not form a palindrome. - Replace all characters to the right of position
iwith the smallest possible characters that do not form a palindrome. - If we reach the start of the string without finding a position to increase, return an empty string.
Solution Code
class Solution {
public String findLexSmallestString(String s, int k) {
char[] arr = s.toCharArray();
int n = arr.length;
for (int i = n - 1; i >= 0; i--) {
if (arr[i] < 'a' + k - 1) {
arr[i]++;
int j = i + 1;
while (j < n) {
if (j - i <= 1 || arr[j - 1] != arr[j - 2]) {
arr[j] = 'a';
} else {
arr[j] = (char) (arr[j - 1] + 1);
}
j++;
}
return new String(arr);
}
}
return "";
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 2663 (Lexicographically Smallest Beautiful String)?
This page provides optimized solutions for LeetCode problem 2663 (Lexicographically Smallest Beautiful String) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 2663 (Lexicographically Smallest Beautiful String)?
The time complexity for LeetCode 2663 (Lexicographically Smallest Beautiful String) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2663 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2663 in Java, C++, or Python.