Lexicographically Smallest Beautiful String - Problem

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.

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: "acba"
💡 Note: Cannot increment 'z', so go to 'c' and increment to 'd', but "abd" contains palindrome. Try 'b'→'c', then build valid suffix: "acba"
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 = "zzab", k = 2
Output: ""
💡 Note: All characters are at maximum for k=2, and no valid increment possible. Return empty string.

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
Beautiful String: Next Lexicographically LargerRequirements: 1) Use first k letters 2) No palindromic substringsInputs = "abdc"k = 4ProcessFind increment at d→eBuild suffix: "a"Output"abea"Beautiful ✓abdcOriginal: "abdc"abeaResult: "abea"Key: Increment d→e, then smallest valid suffix
Understanding the Visualization
1
Input Analysis
Beautiful string s with k allowed characters
2
Find Increment
Locate rightmost position we can increment
3
Build Result
Create lexicographically smallest valid suffix
Key Takeaway
🎯 Key Insight: Work backwards to find the rightmost incrementable position, then build the smallest valid suffix greedily
Asked in
Google 25 Meta 18 Apple 12
24.5K Views
Medium Frequency
~35 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen