Lexicographically Smallest String After Operations With Constraint - Problem
You are given a string s and an integer k, and need to transform s into the lexicographically smallest possible string while staying within a transformation budget.
The Challenge: Letters are arranged in a cyclic order from 'a' to 'z', meaning the distance between 'a' and 'z' is just 1 (wrapping around the circle). The distance function calculates the minimum cyclic distance between corresponding characters in two strings.
For example:
distance("ab", "cd") = 4(a→c costs 2, b→d costs 2)distance("a", "z") = 1(wrap around: a→z or z→a)
Goal: Return the lexicographically smallest string t you can create such that distance(s, t) ≤ k.
Input & Output
example_1.py — Basic Transformation
$
Input:
s = "zab", k = 2
›
Output:
"aab"
💡 Note:
We can change 'z' to 'a' with cost 1 (cyclic distance), resulting in "aab". Total distance = 1, which is ≤ 2.
example_2.py — Limited Budget
$
Input:
s = "xyzab", k = 1
›
Output:
"xyzaa"
💡 Note:
With budget k=1, we can only make one unit change. The best strategy is to change 'b' to 'a' at the end, giving us "xyzaa".
example_3.py — Cyclic Wrapping
$
Input:
s = "ba", k = 1
›
Output:
"aa"
💡 Note:
We can change 'b' to 'a' with cost 1. The cyclic property doesn't matter here since both are close in the alphabet.
Constraints
- 1 ≤ s.length ≤ 105
- 0 ≤ k ≤ 26 × s.length
- s consists only of lowercase English letters
- Cyclic distance: min(|c1 - c2|, 26 - |c1 - c2|)
Visualization
Tap to expand
Understanding the Visualization
1
Analyze Current Character
Look at each position and consider what letters we could change it to
2
Calculate Cyclic Costs
Compute the minimum rotation needed for each possible target letter
3
Budget Planning
Ensure we reserve enough budget for optimizing remaining positions
4
Greedy Selection
Choose the lexicographically smallest affordable option
Key Takeaway
🎯 Key Insight: Use a greedy left-to-right approach where each position is set to the lexicographically smallest possible letter while ensuring the remaining budget can handle the worst-case scenario for future positions.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code