#2663

Lexicographically Smallest Beautiful String

Hard
StringGreedyGreedyTwo PointersBacktracking
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal approach involves modifying the string from the end to the beginning, ensuring that we only change characters when we can maintain the beautiful property. This is more efficient than generating all combinations.

⚙️

Algorithm

5 steps
  1. 1Step 1: Convert the string to a character array for easy manipulation.
  2. 2Step 2: Iterate from the end of the string to the beginning.
  3. 3Step 3: For each character, try to increment it to the next possible character that keeps the string beautiful.
  4. 4Step 4: If you can increment, replace the character and fill the rest with the smallest valid characters to ensure the string is beautiful.
  5. 5Step 5: If no valid string can be formed, return an empty string.
solution.py14 lines
1# Full working Python code
2
3def next_beautiful_string(s, k):
4    n = len(s)
5    s = list(s)
6    for i in range(n - 1, -1, -1):
7        for c in range(ord(s[i]) + 1, ord('a') + k):
8            s[i] = chr(c)
9            if (i < 1 or s[i] != s[i - 1]) and (i < 2 or s[i] != s[i - 2]):
10                for j in range(i + 1, n):
11                    s[j] = 'a' if s[j - 1] != 'a' else 'b'
12                return ''.join(s)
13            s[i] = chr(ord(s[i]) - 1)  # revert back
14    return ""

Complexity note: The complexity is O(n) because we only traverse the string a limited number of times, making it efficient for large inputs.

  • 1A beautiful string cannot have palindromic substrings of length 2 or 3.
  • 2Incrementing characters from the end allows for easier management of the lexicographical order.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.