Lexicographically Smallest Beautiful String - Problem
A beautiful string follows two critical rules:
- It consists only of the first
kletters of the English lowercase alphabet (a, b, c, etc.) - It contains no palindromic substrings of length 2 or more
Given a beautiful string s of length n and a positive integer k, your task is to find the lexicographically smallest string that is:
- Exactly
ncharacters long - Lexicographically larger than
s - Also beautiful according to the rules above
If no such string exists, return an empty string.
Example: For s = "abcb" and k = 4, we need to find the next beautiful string using letters {a,b,c,d}. The answer would be "abdc" because it's the smallest string larger than "abcb" with no palindromic substrings.
Input & Output
example_1.py โ Basic case
$
Input:
s = "abcz", k = 4
โบ
Output:
"abda"
๐ก Note:
The next beautiful string after "abcz" using letters {a,b,c,d}. We increment 'c' to 'd' and fill the last position with 'a' (avoiding palindromes with previous characters 'b' and 'd').
example_2.py โ Cannot increment last character
$
Input:
s = "abc", k = 4
โบ
Output:
"abd"
๐ก Note:
We can increment the last character 'c' to 'd' directly, giving us "abd" which is beautiful and lexicographically larger than "abc".
example_3.py โ No solution exists
$
Input:
s = "dcba", k = 4
โบ
Output:
""
๐ก Note:
Since we're using only letters {a,b,c,d} and "dcba" is already the lexicographically largest possible string with these constraints, no larger beautiful string exists.
Constraints
- 1 โค n โค 105
- 1 โค k โค 26
- s consists of the first k letters of the English lowercase alphabet
- s is guaranteed to be beautiful initially
Visualization
Tap to expand
Understanding the Visualization
1
Identify increment position
Find the rightmost character that can still be incremented (< 'a' + k - 1)
2
Increment the character
Move to the next letter in our allowed alphabet
3
Construct remaining optimally
Fill each subsequent position with the smallest letter that doesn't create palindromes
Key Takeaway
๐ฏ Key Insight: Work backwards to find the rightmost incrementable character, then greedily construct forward while avoiding palindromes with the previous 1-2 characters.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code