Lexicographically Smallest Beautiful String Problem
Description
LeetCode Problem 2663.
A string is beautiful if:
- It consists of the first
kletters of the English lowercase alphabet. - It does not contain any substring of length
2or 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, anddis greater thanc.
Example 1:
Input: s = "abcz", k = 26
Output: "abda"
Explanation: The string "abda" is beautiful and lexicographically larger than the string "abcz".
It can be proven that there is no string that is lexicographically larger than the string "abcz", beautiful, and lexicographically smaller than the string "abda".
Example 2:
Input: s = "dc", k = 4
Output: ""
Explanation: It can be proven that there is no string that is lexicographically larger than the string "dc" and is beautiful.
Constraints:
1 <= n == s.length <= 10^54 <= k <= 26sis a beautiful string.
Solution
Approach: Greedy from the right
A palindrome of length 2 or more always contains a palindrome of length 2 or 3, so a beautiful string is one where every character differs from the two characters before it.
Scan from the last position backwards and look for the first index i whose character can be raised to a larger one among the first k letters while still differing from the two characters before it. Once i is found, keep the prefix, set s[i] to that letter, and fill every later position with the smallest letter that differs from the previous two. That is the smallest beautiful string greater than s. If no index works, return the empty string.
Complexity: time O(n) (each position tries at most a few letters), space O(1) besides the output.
class Solution:
def smallestBeautifulString(self, s: str, k: int) -> str:
n = len(s)
cs = list(s)
for i in range(n - 1, -1, -1):
p = ord(cs[i]) - ord('a') + 1
for j in range(p, k):
c = chr(ord('a') + j)
if (i > 0 and cs[i - 1] == c) or (i > 1 and cs[i - 2] == c):
continue
cs[i] = c
for l in range(i + 1, n):
for m in range(k):
c = chr(ord('a') + m)
if (l > 0 and cs[l - 1] == c) or (l > 1 and cs[l - 2] == c):
continue
cs[l] = c
break
return ''.join(cs)
return ''