Magicsheet logo

Maximum 69 Number

Easy
97.8%
Updated 6/1/2025

Maximum 69 Number

What is this problem about?

You are given a positive integer num consisting only of the digits 6 and 9. You are allowed to change at most one digit (turning a 6 into a 9, or a 9 into a 6). Your objective is to return the maximum possible number you can create.

Why is this asked in interviews?

This is a classic entry-level warmup problem. Interviewers use it to assess basic string manipulation and greedy logic. It quickly verifies if a candidate understands positional math—specifically, that changing a digit in a higher place value (further to the left) yields a much larger overall number than changing a digit on the right.

Algorithmic pattern used

This problem uses a strict Greedy pattern combined with String Traversal. To maximize the number, you want to increase its value. The only way to increase it is to change a 6 to a 9. Because place value dictates magnitude, you must greedily change the very first 6 you encounter from left to right. Converting the integer to a string or character array makes this left-to-right scan trivial.

Example explanation

num = 9669

  1. Convert to string: "9669".
  2. Scan from left to right:
    • Index 0: 9. Leave it.
    • Index 1: 6. Change it to 9! We have used our one allowed change. Break the loop.
  3. The string is now "9969".
  4. Convert back to integer and return 9969.

What if the number is 9999?

  • Scan left to right: no 6 is found.
  • The loop finishes without making changes.
  • Return 9999 (changing a 9 to a 6 would decrease the value, so doing nothing is the optimal choice).

Common mistakes candidates make

A common mistake is iterating from right to left (using modulo 10 math) and changing the first 6 encountered, which actually changes the least significant 6. For 9669, this would yield 9699, which is smaller than 9969. If you solve it using pure math (without strings), you must track the index of the highest 6 you've seen and apply the math addition + 3 * Math.pow(10, highest_six_index) at the very end.

Interview preparation tip

For the Maximum 69 Number coding problem, using string manipulation (String.valueOf(), replaceFirst(), or character arrays) is perfectly acceptable and results in a 3-line solution. However, if the interviewer asks for an O(1)O(1) space solution without string conversions, be prepared to write the modulo loop that tracks the multiplier offset of the leftmost 6.

Similar Questions