← Questions

Largest number by changing up to k digits to 5

0
MicrosoftCoding

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^5
  • 0 <= 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 k changes fine in Part 1?
  • In Part 2, what exactly should "impossible" return: None, an error or an empty string?
  • Can k exceed the length of s?

What a strong answer covers

  • Part 1: goes left to right and changes each digit below 5 while changes remain. Digits above 5 and the 5s 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 5 is changed, spends them on digits above 5, starting from the right, where the loss is smallest.
  • Checks the count of non-5 digits 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, and k larger than the number of changeable digits.

Follow-ups

  • The target digit is a parameter d, not 5.
  • 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

greedy · strings · digits

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding