Lexicographically Smallest Beautiful String - Problem
A string is beautiful if:
- It consists of the first
kletters 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.
For example, "abcd" is lexicographically larger than "abcc" because the first position they differ is at the fourth character, and d is greater than c.
Input & Output
Example 1 — Basic Increment
$
Input:
s = "abcz", k = 4
›
Output:
"abda"
💡 Note:
Cannot increment 'z' (invalid for k=4), backtrack and increment 'c' to 'd', then build smallest valid suffix avoiding palindromes.
Example 2 — Simple Case
$
Input:
s = "abc", k = 4
›
Output:
"abd"
💡 Note:
Can increment last character 'c' to 'd'. Result "abd" has no palindromic substrings and is beautiful.
Example 3 — No Solution
$
Input:
s = "bbab", k = 2
›
Output:
""
💡 Note:
All possible increments lead to palindromes or exceed k=2 limit. No valid next beautiful string exists.
Constraints
- 1 ≤ n ≤ 105
- 1 ≤ k ≤ 4
- s consists of the first k letters of the English lowercase alphabet
- s is beautiful
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code