Lexicographically Smallest Beautiful String - Problem

A beautiful string follows two critical rules:

  • It consists only of the first k letters 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 n characters 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
Beautiful String Construction ProcessOriginal: "abcb" (k=4, letters: a,b,c,d)abcbStep 1: Try rightmost position (b โ†’ c?)abccโœ— Creates "cc" palindrome!Step 2: Try previous position (c โ†’ d)abd?incrementStep 3: Fill optimally (avoid 'd' and 'b')abdaโœ“ 'a' works! (โ‰  'd', โ‰  'b')Final Result: "abda"
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.
Asked in
Google 45 Facebook 32 Amazon 28 Microsoft 15
38.4K Views
Medium Frequency
~25 min Avg. Time
1.2K 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