Magicsheet logo

Max Difference You Can Get From Changing an Integer

Medium
94.5%
Updated 6/1/2025

Max Difference You Can Get From Changing an Integer

What is this problem about?

In this problem, you are given an integer num. You are allowed to perform exactly two operations on it: first, pick a digit xx and replace all occurrences of xx with another digit yy to form a maximum possible number. Second, start over with the original num, pick a digit aa, and replace all occurrences of aa with another digit bb to form a minimum possible number (which cannot contain leading zeroes). Return the difference between the maximum and minimum numbers.

Why is this asked in interviews?

This is a Greedy string manipulation problem. Interviewers use it to test a candidate's practical problem-solving logic. It evaluates whether you can cleanly identify mathematical "best choices" without writing exhaustive permutations. Handling the edge case of "no leading zeroes" accurately separates careful coders from sloppy ones.

Algorithmic pattern used

This problem relies purely on the Greedy pattern.

  1. Convert the integer to a string to easily manipulate digits.
  2. To find the max: Iterate from left to right. Find the first digit that is not 9. Greedily replace all occurrences of this digit with 9. (If all are 9, the number is already maxed).
  3. To find the min: Iterate from left to right.
    • If the very first digit is not 1, replace it with 1. (You can't use 0 because no leading zeroes are allowed).
    • If the first digit is 1, find the first subsequent digit that is not 0 or 1, and replace all its occurrences with 0.

Example explanation

num = 123456 Max number:

  • First digit is 1. It's not 9. Replace all 1s with 9.
  • Max = 923456.

Min number:

  • First digit is 1. We can't change it to 0. It's already the smallest valid start.
  • Second digit is 2. It's not 0 or 1. Replace all 2s with 0.
  • Min = 103456.

Difference = 923456 - 103456 = 820000.

Common mistakes candidates make

The most frequent mistake is generating the minimum number incorrectly by replacing the first digit with 0. The prompt strictly forbids leading zeroes in the resulting integer (meaning a number can't start with 0 unless the number itself is just 0, which doesn't apply here as num > 0). Another mistake is forgetting that replacing a digit replaces all occurrences of that digit globally throughout the string.

Interview preparation tip

When tackling the Max Difference You Can Get From Changing an Integer interview question, write two separate, dedicated helper functions: getMax(numStr) and getMin(numStr). By isolating the greedy rules for maximization (always target the first non-9) from the minimization rules (handle the leading digit separately from the rest), your code will be vastly more readable and bug-free.

Similar Questions