Magicsheet logo

Lexicographically Smallest Beautiful String

Hard
12.5%
Updated 8/1/2025

Asked by 2 Companies

Lexicographically Smallest Beautiful String

What is this problem about?

The "Lexicographically Smallest Beautiful String interview question" is a difficult string construction problem. A "beautiful" string is defined as one that does not contain any palindromic substrings of length 2 or 3. You are given a beautiful string and must find the lexicographically smallest beautiful string that is larger than the input. This "Lexicographically Smallest Beautiful String coding problem" is a test of your ability to perform greedy increments while maintaining global constraints.

Why is this asked in interviews?

This problem is asked by companies like Amazon to evaluate a candidate's grasp of the "Greedy interview pattern" and their ability to handle string invariants. It requires a deep understanding of palindromes (length 2 means s[i] == s[i-1], length 3 means s[i] == s[i-2]) and how to efficiently modify a string to satisfy these conditions from left to right.

Algorithmic pattern used

The strategy is to try incrementing the string starting from the last character. If we can't increment without violating the beautiful property or exceeding the allowed character range, we move one index to the left and try again. Once we find a valid increment, we fill the rest of the string to the right with the smallest possible characters ('a', 'b', 'c') that don't create palindromes with their predecessors.

Example explanation

String: "abcz", k=4 (chars up to 'd').

  1. Try to increment 'z': can't, out of range.
  2. Move to 'c', increment to 'd'. Check palindromes: "ab d". 'd' is not 'b' or 'c'. Valid.
  3. Fill remaining (none here). Result: "ab d". If the string was longer, we'd fill subsequent positions with the smallest available characters.

Common mistakes candidates make

  • Checking all palindromes: Not realizing that you only need to check length 2 and 3 palindromes to ensure no palindromes exist.
  • Missing the "larger than" requirement: Not correctly identifying the rightmost position that can be incremented.
  • Inefficient fills: Not greedily filling the right-hand side with the smallest possible values ('a', 'b', 'c').

Interview preparation tip

Palindromic constraints are often local. A string has no palindromes if and only if no character is the same as its immediate neighbor or the character before that. This insight simplifies many "no palindrome" problems significantly.

Similar Questions