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
Lexicographically Smallest String INPUT Cyclic Order (a-z) a b c d ... n ... y z Input String s: z [0] a [1] b [2] k = 2 ALGORITHM STEPS 1 Process Left-to-Right Greedy: prefer smaller chars 2 Position 0: 'z' dist(z,a)=1, k=2-1=1 z --> a 3 Position 1: 'a' dist(a,a)=0, k=1-0=1 a --> a 4 Position 2: 'b' dist(b,a)=1, k=1-1=0 b --> a Total Distance Used: 1 + 0 + 1 = 2 <= k FINAL RESULT Transformation Complete Original: z a b Result: a a a Output: "aaa" OK - Lexicographically Smallest Key Insight: Greedy approach: Process characters left-to-right. For each position, try to change to 'a' first (lexicographically smallest). If distance cost exceeds remaining k, try 'b', 'c', etc. Cyclic distance: min(|c1-c2|, 26-|c1-c2|). Example: dist('z','a') = min(25,1) = 1 TutorialsPoint - Lexicographically Smallest String After Operations With Constraint | Greedy Approach
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