1323. Maximum 69 Number
Problem Description
You are given a positive integer num
that contains only the digits 6
and 9
.
Your task is to find the maximum number you can create by changing at most one digit in the number. You can change a 6
to a 9
, or change a 9
to a 6
.
For example:
- If
num = 9669
, you can change the first6
to get9969
, which is the maximum possible - If
num = 9996
, you can change the last6
to get9999
- If
num = 9999
, you don't need to change anything since it's already the maximum
The solution uses a greedy approach: to maximize the number, we want to change the leftmost 6
to a 9
(if any exists). This is because changing a digit in a more significant position has a greater impact on the final value. The code converts the number to a string, replaces the first occurrence of "6"
with "9"
using replace("6", "9", 1)
where the third parameter 1
ensures only the first 6
is replaced, then converts back to an integer.
Intuition
To maximize a number, we want the leftmost (most significant) digits to be as large as possible. Since our number only contains 6
and 9
, and 9
is larger than 6
, we want as many 9
s as possible, especially in the higher-value positions.
When we can change at most one digit, we need to decide which digit change would give us the biggest increase. Changing a 6
to a 9
increases the value, while changing a 9
to a 6
decreases it. So we should only consider changing 6
to 9
.
But which 6
should we change if there are multiple? Consider these examples:
- Changing
6669
→ the first6
gives us9669
(increase of 3000) - Changing
6669
→ the second6
gives us6969
(increase of 300) - Changing
6669
→ the third6
gives us6699
(increase of 30)
The pattern is clear: changing a digit in a higher position gives a larger increase. The leftmost 6
represents the highest place value among all 6
s in the number, so changing it to 9
will give us the maximum possible increase.
If the number contains no 6
s (like 9999
), then we can't improve it further, and the original number is already the maximum.
This leads us to the simple strategy: find the first 6
from the left and change it to 9
. If there's no 6
, keep the number as is.
Solution Approach
The implementation follows a straightforward greedy approach by converting the number to a string for easy manipulation:
-
Convert number to string: We first convert the integer
num
to a string usingstr(num)
. This allows us to easily access and manipulate individual digits. -
Find and replace the first '6': We use Python's
replace()
method with the syntaxreplace("6", "9", 1)
. The key parameters are:- First parameter
"6"
: the character to search for - Second parameter
"9"
: the character to replace it with - Third parameter
1
: limits the replacement to only the first occurrence
This ensures we only change the leftmost
6
to9
, which gives us the maximum possible value. - First parameter
-
Convert back to integer: After the replacement, we convert the resulting string back to an integer using
int()
.
The beauty of this solution lies in its simplicity. The replace()
method with the limit parameter handles all the logic:
- If there's at least one
6
, it replaces only the first one (leftmost) - If there are no
6
s in the number, the string remains unchanged - No need for loops or conditional statements
Time Complexity: O(n)
where n
is the number of digits, as we need to convert to string and potentially scan for the first 6
.
Space Complexity: O(n)
for storing the string representation of the number.
This one-liner solution elegantly captures the greedy strategy: maximize the number by changing the most significant 6
to 9
.
Ready to land your dream job?
Unlock your dream job with a 3-minute evaluator for a personalized learning plan!
Start EvaluatorExample Walkthrough
Let's walk through the solution with num = 6996
:
Step 1: Convert to string
num = 6996
becomes"6996"
Step 2: Find the first '6' and replace with '9'
- Scanning from left to right, the first '6' is at position 0
- Using
replace("6", "9", 1)
:- The method searches for "6" in the string "6996"
- It finds the first occurrence at index 0
- It replaces only this first "6" with "9" (due to the limit parameter
1
) - Result:
"9996"
Step 3: Convert back to integer
"9996"
becomes9996
Why this gives the maximum:
- Original number:
6996
- If we changed the first '6' →
9996
(increase of 3000) ✓ This is what we did - If we changed the second '6' →
6996
(no change, same position) - If we changed any '9' to '6' → would decrease the value
The algorithm correctly identifies that changing the leftmost '6' to '9' produces the maximum value of 9996
.
Another example with no changes needed:
For num = 9999
:
- Convert to string:
"9999"
- Try to replace first '6' with '9': No '6' found, string remains
"9999"
- Convert back:
9999
- The number stays the same, which is correct since it's already maximized.
Solution Implementation
1class Solution:
2 def maximum69Number(self, num: int) -> int:
3 """
4 Given a positive integer num consisting only of digits 6 and 9,
5 return the maximum number you can get by changing at most one digit.
6
7 Args:
8 num: A positive integer consisting only of digits 6 and 9
9
10 Returns:
11 The maximum number after changing at most one digit
12 """
13 # Convert the number to string for easier manipulation
14 num_str = str(num)
15
16 # Replace the first occurrence of '6' with '9' to maximize the number
17 # The replace method with count=1 ensures only the first '6' is replaced
18 # This gives us the maximum possible value since replacing the leftmost '6'
19 # with '9' yields the largest increase
20 modified_str = num_str.replace("6", "9", 1)
21
22 # Convert the modified string back to integer and return
23 return int(modified_str)
24
1class Solution {
2 /**
3 * Returns the maximum number by changing at most one digit.
4 * The input number consists only of digits 6 and 9.
5 * Strategy: Replace the first (leftmost) occurrence of 6 with 9 to maximize the value.
6 *
7 * @param num the input number containing only digits 6 and 9
8 * @return the maximum possible number after changing at most one digit
9 */
10 public int maximum69Number(int num) {
11 // Convert the number to string for digit manipulation
12 String numString = String.valueOf(num);
13
14 // Replace the first occurrence of '6' with '9' to maximize the value
15 // If no '6' exists, the string remains unchanged
16 String modifiedString = numString.replaceFirst("6", "9");
17
18 // Convert the modified string back to integer and return
19 return Integer.parseInt(modifiedString);
20 }
21}
22
1class Solution {
2public:
3 int maximum69Number(int num) {
4 // Convert the integer to string for easier digit manipulation
5 string numStr = to_string(num);
6
7 // Iterate through each digit from left to right
8 for (char& digit : numStr) {
9 // Find the first occurrence of '6' and change it to '9'
10 if (digit == '6') {
11 digit = '9';
12 break; // Exit after changing the first '6' to maximize the result
13 }
14 }
15
16 // Convert the modified string back to integer and return
17 return stoi(numStr);
18 }
19};
20
1/**
2 * Converts the first occurrence of digit '6' to '9' in the given number
3 * to maximize the resulting value.
4 *
5 * @param num - The input number containing digits 6 and/or 9
6 * @returns The maximum number after changing at most one digit
7 */
8function maximum69Number(num: number): number {
9 // Convert number to string for digit manipulation
10 const numStr: string = num.toString();
11
12 // Replace the first occurrence of '6' with '9' to maximize the value
13 // If no '6' exists, the string remains unchanged
14 const modifiedStr: string = numStr.replace('6', '9');
15
16 // Convert the modified string back to a number and return
17 return Number(modifiedStr);
18}
19
Time and Space Complexity
Time Complexity: O(log num)
The time complexity is determined by the following operations:
- Converting the integer
num
to a string:O(log num)
- the number of digits innum
is proportional tolog num
- The
replace()
method with limit 1:O(log num)
- it needs to scan through the string until it finds the first '6' or reaches the end - Converting the string back to an integer:
O(log num)
Since all operations are O(log num)
and they're performed sequentially, the overall time complexity is O(log num)
.
Space Complexity: O(log num)
The space complexity comes from:
- Creating a string representation of
num
:O(log num)
- the string length equals the number of digits - The
replace()
method creates a new string:O(log num)
- Python strings are immutable, so a new string of the same length is created - The intermediate string objects before conversion back to integer
Therefore, the space complexity is O(log num)
as we need to store strings with length proportional to the number of digits in num
.
Learn more about how to find time and space complexity quickly.
Common Pitfalls
1. Attempting to Replace Multiple Digits
A common misunderstanding is thinking we need to replace ALL occurrences of '6' with '9' to maximize the number. This would be incorrect since the problem states we can change "at most one digit."
Incorrect approach:
# Wrong: This replaces ALL '6's with '9's
def maximum69Number(self, num: int) -> int:
return int(str(num).replace("6", "9")) # Missing the count parameter
Why it fails: For num = 6669
, this would return 9999
instead of the correct answer 9669
(only the first '6' should be changed).
Solution: Always use the count parameter in replace()
method: replace("6", "9", 1)
2. Trying to Change '9' to '6' When No '6' Exists
Some might think that if there are no '6's in the number, we should change a '9' to '6'. This is incorrect because changing any '9' to '6' would decrease the number, not maximize it.
Incorrect logic:
def maximum69Number(self, num: int) -> int:
num_str = str(num)
if '6' in num_str:
return int(num_str.replace("6", "9", 1))
else:
# Wrong: Don't change '9' to '6'
return int(num_str.replace("9", "6", 1))
Why it fails: For num = 9999
, this would return 6999
which is smaller than the original.
Solution: The problem asks for "at most one" change, meaning zero changes is valid. If there are no '6's, leave the number unchanged.
3. Replacing the Wrong '6' (Not the Leftmost)
Using complex logic to find and replace a '6' other than the leftmost one, perhaps thinking about replacing the "largest" '6' or using different criteria.
Incorrect approach:
def maximum69Number(self, num: int) -> int:
num_str = str(num)
# Wrong: Replacing the last '6' instead of the first
if '6' in num_str:
idx = num_str.rfind('6') # Finds rightmost '6'
num_str = num_str[:idx] + '9' + num_str[idx+1:]
return int(num_str)
Why it fails: For num = 6996
, this would return 6999
instead of the correct answer 9996
.
Solution: Always replace the leftmost (first) '6' since changing a more significant digit has a greater impact on the final value.
What are the two properties the problem needs to have for dynamic programming to be applicable? (Select 2)
Recommended Readings
Greedy Introduction div class responsive iframe iframe src https www youtube com embed WTslqPbj7I title YouTube video player frameborder 0 allow accelerometer autoplay clipboard write encrypted media gyroscope picture in picture web share allowfullscreen iframe div When do we use greedy Greedy algorithms tend to solve optimization problems Typically they will ask you to calculate the max min of some value Commonly you may see this phrased in the problem as max min longest shortest largest smallest etc These keywords can be identified by just scanning
Math for Technical Interviews How much math do I need to know for technical interviews The short answer is about high school level math Computer science is often associated with math and some universities even place their computer science department under the math faculty However the reality is that you
Coding Interview Patterns Your Personal Dijkstra's Algorithm to Landing Your Dream Job The goal of AlgoMonster is to help you get a job in the shortest amount of time possible in a data driven way We compiled datasets of tech interview problems and broke them down by patterns This way
Want a Structured Path to Master System Design Too? Don’t Miss This!