Lexicographically Smallest String After Operations With Constraint - Problem
You are given a string s and an integer k. Define a function distance(s1, s2) between two strings s1 and s2 of the same length n as:
The sum of the minimum distance between s1[i] and s2[i] when the characters from 'a' to 'z' are placed in a cyclic order, for all i in 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.
Input & Output
Example 1 — Basic Transformation
$
Input:
s = "zab", k = 2
›
Output:
"aaa"
💡 Note:
Change 'z' to 'a' (cost 1), 'a' stays 'a' (cost 0), change 'b' to 'a' (cost 1). Total cost = 2 ≤ k.
Example 2 — Limited Budget
$
Input:
s = "xkcd", k = 4
›
Output:
"akcd"
💡 Note:
Change 'x' to 'a' (cost 3), remaining budget is 1. 'k' to 'a' costs 10 > 1, so 'k' stays. 'c' and 'd' also stay due to insufficient budget.
Example 3 — Insufficient Budget
$
Input:
s = "abc", k = 0
›
Output:
"abc"
💡 Note:
No budget available, string remains unchanged.
Constraints
- 1 ≤ s.length ≤ 105
- 0 ≤ k ≤ 2 × 105
- s consists of lowercase English letters only
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code