Practice/Amazon/Leetcode 2663. Lexicographically Smallest Beautiful String
CodingOptional
You are given a string s consisting only of the first k lowercase English letters (from 'a' to the k-th letter). The string is called beautiful if it does not contain any palindromic substring of length 2 or greater.
A palindromic substring of length 2 means two adjacent identical characters (like "aa"). A palindromic substring of length 3 means a pattern where the first and third characters are the same (like "aba").
Your task is to find the lexicographically smallest string of the same length as s that is:
s in lexicographic orderk letters of the alphabetIf no such string exists, return an empty string.
i can equal the character at position i-2 (to prevent palindromes like "aba")s is guaranteed to be beautifuls are within the first k lettersExample 1:
Input: s = "abac", k = 3 Output: "abca" Explanation: Starting from "abac", we need the next valid string. Incrementing the last character from 'c' to the next would exceed our limit, so we backtrack. We can change position 2 from 'a' to 'c' and set position 3 to 'a', giving us "abca" which has no palindromic substrings.
Example 2:
Input: s = "abc", k = 4 Output: "aca" Explanation: We try to increment from the rightmost position. Since we can't simply increment 'c' while maintaining the beautiful property with the available characters, we backtrack and find "aca" as the next valid configuration.
Example 3:
Input: s = "ab", k = 3 Output: "ac" Explanation: Simple increment of the last character from 'b' to 'c' maintains all constraints.