2663. Lexicographically Smallest Beautiful String
Explanation
To find the lexicographically smallest beautiful string larger than the given string s
, we can follow these steps:
- Iterate through the string
s
from right to left to find the first positioni
where 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
i
with 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.
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 "";
}
}
Code Editor (Testing phase)
Improve Your Solution
Use the editor below to refine the provided solution. Select a programming language and try the following:
- Add import statement if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.