Lexicographically Smallest String After Operations With Constraint Problem
Description
LeetCode Problem 3106.
You are given a string s and an integer k.
Define a function distance(s_1, s_2) between two strings s_1 and s_2 of the same length n as:
- The sum of the minimum distance between
s_1[i]ands_2[i]when the characters from'a'to'z'are placed in a cyclic order, for alliin the range[0, n - 1].
For example, distance("ab", "cd") == 4, and distance("a", "z") == 1.
You can change any letter of s to any other lowercase English letter, any number of times.
Return a string denoting the lexicographically smallest string t you can get after some changes, such that distance(s, t) <= k.
Example 1:
Input: s = "zbbz", k = 3
Output: "aaaz"
Explanation:
Change s to "aaaz". The distance between "zbbz" and "aaaz" is equal to k = 3.
Example 2:
Input: s = "xaxcd", k = 4
Output: "aawcd"
Explanation:
The distance between "xaxcd" and "aawcd" is equal to k = 4.
Example 3:
Input: s = "lol", k = 0
Output: "lol"
Explanation:
It's impossible to change any character as k = 0.
Constraints:
1 <= s.length <= 1000 <= k <= 2000sconsists only of lowercase English letters.
Solution
Approach: Greedy
Go through the string from left to right. At each position try the letters from a upward that are smaller than the current one; the cyclic cost of changing c1 into c2 is min(c1 - c2, 26 - c1 + c2). Take the first letter whose cost d is within the remaining budget k, subtract d from k, and move on. Spending the budget on the earliest positions with the smallest letters gives the lexicographically smallest string.
Complexity: O(26 n) time and O(n) space.
class Solution:
def getSmallestString(self, s: str, k: int) -> str:
cs = list(s)
for i, c1 in enumerate(s):
for c2 in "abcdefghijklmnopqrstuvwxyz":
if c2 >= c1:
break
d = min(ord(c1) - ord(c2), 26 - ord(c1) + ord(c2))
if d <= k:
cs[i] = c2
k -= d
break
return "".join(cs)