Largest number by changing up to k digits to 5
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked at Microsoft. It tests greedy, strings and digits.
You are given a string s that holds a positive integer (digits only, no leading zero) and an integer k.
In one operation you pick any digit of s that is not 5 and change it to 5. You may perform at most k operations.
Implement:
def maximize_with_fives(s: str, k: int) -> str: ...
Return the largest number you can obtain, as a string.
Constraints
1 <= len(s) <= 10^50 <= k <= 10^5- The number may be too large for a 64-bit integer, so work with the string.
Example 1
s = "1234", k = 2
output: "5534"
Change the 1 and the 2. Changing the 3 or 4 instead gives a smaller result.
Example 2
s = "9183", k = 1
output: "9583"
The leading 9 would get smaller, so leave it. The best single change is the 1.
Part 2. Now you must use exactly k operations. Return the largest result, or report that it is impossible when s has fewer than k digits that are not 5.
Clarifying questions
- Can a change ever make the number smaller and still help? (Not in Part 1.)
- Is a result with fewer than
kchanges fine in Part 1? - In Part 2, what exactly should "impossible" return:
None, an error or an empty string? - Can
kexceed the length ofs?
What a strong answer covers
- Part 1: goes left to right and changes each digit below
5while changes remain. Digits above5and the5s stay. That is O(n). - Explains why left to right: a higher place value always wins.
- Part 2: if changes are left after every digit below
5is changed, spends them on digits above5, starting from the right, where the loss is smallest. - Checks the count of non-
5digits first, to report impossibility. - Builds the result with a list of characters, not repeated string concatenation.
- Tests both examples,
k = 0, all fives, all nines, andklarger than the number of changeable digits.
Follow-ups
- The target digit is a parameter
d, not5. - Make the smallest number instead.
- Each change costs the distance between the digits, within a budget.
- Changes must be to adjacent positions only.
Where it's asked
What it tests
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. New accounts get 5 credits: each one unlocks a question for good.
What the labs asked this week
A weekly email of what OpenAI, Anthropic and the other top AI labs asked engineers, round by round.
Sign in to submit your code; every attempt is kept here.
