Maximum 69 Number
EasyPrompt
You are given a positive integer num consisting only of digits 6 and 9.
Return the maximum number you can get by changing at most one digit (6 becomes 9, and 9 becomes 6).
Example 1:
Input: num = 9669
Output: 9969
Explanation:
Changing the first digit results in 6669.
Changing the second digit results in 9969.
Changing the third digit results in 9699.
Changing the fourth digit results in 9666.
The maximum number is 9969.Example 2:
Input: num = 9996
Output: 9999
Explanation: Changing the last digit 6 to 9 results in the maximum number.Example 3:
Input: num = 9999
Output: 9999
Explanation: It is better not to apply any change.
Constraints:
1 <= num <= 104numconsists of only6and9digits.
Approaches
3 approaches with complexity analysis and trade-offs.
This approach involves generating every possible number that can be formed by changing a single digit of the input number. We then find the maximum among all the generated numbers, including the original number.
Algorithm
-
- Convert the input integer
numto its string representation,s.
- Convert the input integer
-
- Initialize a variable
maxNumwith the value ofnum.
- Initialize a variable
-
- Iterate through the string
sfrom the first character to the last.
- Iterate through the string
-
- For each character, create a temporary character array from
s.
- For each character, create a temporary character array from
-
- If the character at the current index
iis '6':
- If the character at the current index
-
- Change the character at index
iin the temporary array to '9'.
- Change the character at index
-
- Convert the modified character array back to an integer,
newNum.
- Convert the modified character array back to an integer,
-
- Update
maxNumto be the maximum ofmaxNumandnewNum.
- Update
-
- After the loop finishes, return
maxNum.
- After the loop finishes, return
Walkthrough
This method exhaustively checks all possibilities. We convert the number to a character array and iterate through each position. If the digit at the current position is '6', we change it to '9', convert the result back to an integer, and compare it with the maximum number found so far. The initial maximum is the input number itself. This method is guaranteed to work but is inefficient because it continues to check possibilities even after the optimal one (the first '6') has been found.
class Solution { public int maximum69Number (int num) { String s = Integer.toString(num); int maxNum = num; for (int i = 0; i < s.length(); i++) { char[] chars = s.toCharArray(); if (chars[i] == '6') { chars[i] = '9'; maxNum = Math.max(maxNum, Integer.parseInt(new String(chars))); } } return maxNum; }}Complexity
Time
O(d^2), where `d` is the number of digits in `num`. The loop runs `d` times. Inside the loop, converting the string to a character array, creating a new string, and parsing it to an integer each take O(d) time.
Space
O(d), where `d` is the number of digits. This space is used to store the string representation and the character array.
Trade-offs
Pros
Simple to understand and implement.
Guaranteed to find the correct answer by checking all relevant possibilities.
Cons
Inefficient due to repeated conversions between string and integer inside a loop.
Performs more work than necessary, as the optimal change is always at the first '6'.
A more efficient approach is to realize that to maximize the number, we should change the most significant '6' to a '9'. This means we only need to find the first occurrence of '6' from the left and change it. If no '6' exists, the number is already maximized.
Algorithm
-
- Convert the input integer
numto a character arraychars.
- Convert the input integer
-
- Iterate through the
charsarray from left to right (indexifrom 0 to length-1).
- Iterate through the
-
- If the character at the current index
iis '6':
- If the character at the current index
-
- Change this character to '9'.
-
- Convert the modified character array back to a string, then parse it to an integer.
-
- Return the resulting integer immediately, as we have found the leftmost '6' and made the optimal change.
-
- If the loop completes without finding any '6', it means the number consists only of '9's.
-
- In this case, return the original
num.
- In this case, return the original
Walkthrough
This method leverages string manipulation to find and replace the target digit. First, the integer num is converted to a string or character array. We then iterate from left to right, looking for the first '6'. Once found, we replace it with a '9', convert the modified representation back to an integer, and return it immediately. This is optimal because changing a more significant digit has a greater impact. If the loop finishes without finding a '6', it means the number is already maximized (e.g., 9999), so we return the original number.
class Solution { public int maximum69Number (int num) { char[] chars = Integer.toString(num).toCharArray(); for (int i = 0; i < chars.length; i++) { if (chars[i] == '6') { chars[i] = '9'; return Integer.parseInt(new String(chars)); } } return num; }}Alternatively, one could use the built-in replaceFirst method for a more concise solution:
class Solution { public int maximum69Number (int num) { return Integer.parseInt(Integer.toString(num).replaceFirst("6", "9")); }}Complexity
Time
O(d), where `d` is the number of digits in `num`. Converting the number to a string/char array takes O(d). The loop runs at most `d` times. Converting the result back to an integer also takes O(d). The total complexity is linear.
Space
O(d), for storing the string or character array representation of the number, where `d` is the number of digits.
Trade-offs
Pros
Much more efficient than the brute-force approach.
Simple logic: find the first '6' and change it.
Easy to implement using standard string/array functions.
Cons
Requires conversions between integer and string/array types, which can have some overhead.
Uses extra space proportional to the number of digits.
This is the most optimal approach, avoiding any string conversions. It works by mathematically identifying the position of the leftmost '6' and adding the appropriate value to change it to a '9'.
Algorithm
-
- Initialize
valueToAdd = 0. This will store the value that needs to be added tonumto make the change.
- Initialize
-
- Initialize
powerOf10 = 1. This will represent the current place value (1, 10, 100, ...).
- Initialize
-
- Create a temporary copy of the input number,
tempNum = num.
- Create a temporary copy of the input number,
-
- Loop while
tempNumis greater than 0:
- Loop while
-
- Get the rightmost digit:
digit = tempNum % 10.
- Get the rightmost digit:
-
- If
digitis 6, we updatevalueToAddto3 * powerOf10. Since we iterate from right to left, this variable will be overwritten by subsequent '6's found at higher place values, ensuring it ultimately holds the value corresponding to the leftmost '6'.
- If
-
- Update
tempNumto process the next digit:tempNum /= 10.
- Update
-
- Update the place value:
powerOf10 *= 10.
- Update the place value:
-
- After the loop,
valueToAddwill be0if no '6' was found, or3 * 10^kif the leftmost '6' was at positionk.
- After the loop,
-
- Return
num + valueToAdd.
- Return
Walkthrough
The core idea is to find the place value (units, tens, hundreds, etc.) of the leftmost '6'. We can do this by iterating through the digits of the number from right to left. We keep track of the position of the last '6' we encounter during this scan, which corresponds to the leftmost '6' in the number. Changing a '6' to a '9' is equivalent to adding 3 at that digit's place. For example, in 9669, the leftmost '6' is in the hundreds place. Changing it to '9' means adding 3 * 100 = 300, resulting in 9669 + 300 = 9969. If no '6' is found, we add nothing.
class Solution { public int maximum69Number (int num) { int tempNum = num; int powerOf10 = 1; int valueToAdd = 0; while (tempNum > 0) { int digit = tempNum % 10; if (digit == 6) { // This will be updated for each '6' we find. // The last update will correspond to the leftmost '6'. valueToAdd = 3 * powerOf10; } tempNum /= 10; powerOf10 *= 10; } return num + valueToAdd; }}Complexity
Time
O(d), where `d` is the number of digits in `num` (or O(log10(num))). The while loop iterates once for each digit of the number.
Space
O(1). This approach uses only a few extra variables to store state, regardless of the size of the input number.
Trade-offs
Pros
Most efficient in terms of both time and space.
Avoids overhead of string conversions and memory allocations.
Elegant solution using basic arithmetic operations.
Cons
The logic might be slightly less intuitive to grasp at first compared to the straightforward string manipulation approach.
Solutions
Solution
class Solution {public int maximum69Number(int num) { return Integer.valueOf(String.valueOf(num).replaceFirst("6", "9")); }}class Solution {public: int maximum69Number(int num) { string s = to_string(num); for (char &ch : s) { if (ch == '6') { ch = '9'; break; } } return stoi(s); }};class Solution: def maximum69Number( self, num: int) -> int: return int(str(num). replace("6", "9", 1))Video walkthrough
Newsletter
One sharp idea, every week
System design and interview prep — short enough to finish.
No spam. Unsubscribe anytime.
Practice
Same difficulty — related problems to reinforce the pattern.