Using greedy without proof
Wrong move: Locally optimal choices may fail globally.
Usually fails on: Counterexamples appear on crafted input orderings.
Fix: Verify with exchange argument or monotonic objective before committing.
Move from brute-force thinking to an efficient approach using greedy strategy.
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:
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.
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 <= 2000s consists only of lowercase English letters.Problem summary: 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Greedy
"zbbz" 3
"xaxcd" 4
"lol" 0
lexicographically-smallest-string-after-substring-operation)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #3106: Lexicographically Smallest String After Operations With Constraint
class Solution {
public String getSmallestString(String s, int k) {
char[] cs = s.toCharArray();
for (int i = 0; i < cs.length; ++i) {
char c1 = cs[i];
for (char c2 = 'a'; c2 < c1; ++c2) {
int d = Math.min(c1 - c2, 26 - c1 + c2);
if (d <= k) {
cs[i] = c2;
k -= d;
break;
}
}
}
return new String(cs);
}
}
// Accepted solution for LeetCode #3106: Lexicographically Smallest String After Operations With Constraint
func getSmallestString(s string, k int) string {
cs := []byte(s)
for i, c1 := range cs {
for c2 := byte('a'); c2 < c1; c2++ {
d := int(min(c1-c2, 26-c1+c2))
if d <= k {
cs[i] = c2
k -= d
break
}
}
}
return string(cs)
}
# Accepted solution for LeetCode #3106: Lexicographically Smallest String After Operations With Constraint
class Solution:
def getSmallestString(self, s: str, k: int) -> str:
cs = list(s)
for i, c1 in enumerate(s):
for c2 in ascii_lowercase:
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)
// Accepted solution for LeetCode #3106: Lexicographically Smallest String After Operations With Constraint
// Rust example auto-generated from java reference.
// Replace the signature and local types with the exact LeetCode harness for this problem.
impl Solution {
pub fn rust_example() {
// Port the logic from the reference block below.
}
}
// Reference (java):
// // Accepted solution for LeetCode #3106: Lexicographically Smallest String After Operations With Constraint
// class Solution {
// public String getSmallestString(String s, int k) {
// char[] cs = s.toCharArray();
// for (int i = 0; i < cs.length; ++i) {
// char c1 = cs[i];
// for (char c2 = 'a'; c2 < c1; ++c2) {
// int d = Math.min(c1 - c2, 26 - c1 + c2);
// if (d <= k) {
// cs[i] = c2;
// k -= d;
// break;
// }
// }
// }
// return new String(cs);
// }
// }
// Accepted solution for LeetCode #3106: Lexicographically Smallest String After Operations With Constraint
function getSmallestString(s: string, k: number): string {
const cs: string[] = s.split('');
for (let i = 0; i < s.length; ++i) {
for (let j = 97; j < s[i].charCodeAt(0); ++j) {
const d = Math.min(s[i].charCodeAt(0) - j, 26 - s[i].charCodeAt(0) + j);
if (d <= k) {
cs[i] = String.fromCharCode(j);
k -= d;
break;
}
}
}
return cs.join('');
}
Use this to step through a reusable interview workflow for this problem.
Try every possible combination of choices. With n items each having two states (include/exclude), the search space is 2ⁿ. Evaluating each combination takes O(n), giving O(n × 2ⁿ). The recursion stack or subset storage uses O(n) space.
Greedy algorithms typically sort the input (O(n log n)) then make a single pass (O(n)). The sort dominates. If the input is already sorted or the greedy choice can be computed without sorting, time drops to O(n). Proving greedy correctness (exchange argument) is harder than the implementation.
Review these before coding to avoid predictable interview regressions.
Wrong move: Locally optimal choices may fail globally.
Usually fails on: Counterexamples appear on crafted input orderings.
Fix: Verify with exchange argument or monotonic objective before committing.