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: "aakd"
💡 Note: Change 'x' to 'a' (cost 3), change 'k' to 'a' (cost 10, too expensive) → 'k' stays, 'c' stays, 'd' stays. Only 1 budget left.
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
Transform String to Lexicographically SmallestInput: s = "zab"Budget: k = 2Output: "aaa"Distance used: 2zabcost: 1cost: 0cost: 1aaaCyclic distance: z↔a = min(|z-a|, 26-|z-a|) = min(25, 1) = 1Greedy approach ensures lexicographically smallest result
Understanding the Visualization
1
Input
String "zab" with budget k=2
2
Process
Greedily transform each character to 'a' if budget allows
3
Output
Result "aaa" with total distance 2
Key Takeaway
🎯 Key Insight: Process characters left-to-right, always prioritizing 'a' to achieve lexicographically smallest string
Asked in
Google 25 Amazon 18 Microsoft 15 Meta 12
23.4K Views
Medium Frequency
~15 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen