Problem Description
A string is beautiful if:
- It consists of the first
k
letters of the English lowercase alphabet. - It does not contain any substring of length
2
or more which is a palindrome.
You are given a beautiful string s
of length n
and a positive integer k
.
Return the lexicographically smallest string of length n
, which is larger than s
and is beautiful. If there is no such string, return an empty string.
A string a
is lexicographically larger than a string b
(of the same length) if in the first position where a
and b
differ, a
has a character strictly larger than the corresponding character in b
.
Key Insights
- The string must consist only of the first
k
letters of the alphabet. - To ensure that the string does not contain palindromic substrings of length
2
or more, we need to avoid consecutive identical characters. - We can use a greedy approach to construct the next lexicographical string by iterating from the end of the string
s
backward.
Space and Time Complexity
Time Complexity: O(n)
Space Complexity: O(n)
Solution
The solution involves creating a new string that is a modified version of the input string s
. We will iterate backward from the last character of s
, looking for the first character that can be incremented while ensuring the new character does not lead to a palindrome.
The algorithm works as follows:
- Start from the end of the string and attempt to increment the character.
- If incrementing causes a palindrome, try to replace it with the next valid character that does not create a palindrome.
- If the character cannot be incremented or replaced without violating the conditions, continue moving left.
- If we reach the start of the string and cannot find a valid solution, return an empty string.