Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
123 Number Flip in Python
Suppose we have an integer n, where only digits 1, 2, and 3 are present. We can flip one digit to a 3. The goal is to find the maximum number we can make.
So, if the input is like 11332, then the output will be 31332.
Approach
To solve this, we will follow these steps ?
Convert the number into a list of digits
Iterate through each digit from left to right
If we find the first digit that is not '3', change it to '3'
Return the modified number
If all digits are already '3', return the original number
Example
Let us see the following implementation to get better understanding ?
class Solution:
def solve(self, n):
digits = list(str(n))
for x in range(len(digits)):
if digits[x] != '3':
digits[x] = '3'
return int(''.join(digits))
return n
ob = Solution()
print(ob.solve(11332))
31332
How It Works
The algorithm works by finding the leftmost digit that is not '3' and changing it to '3'. This maximizes the number because:
We want to change the most significant digit possible
Changing a digit to '3' (the highest allowed digit) increases the value
We scan from left to right to find the first opportunity
Alternative Implementation
Here's a more concise version using string operations ?
def maximize_number(n):
s = str(n)
for i, digit in enumerate(s):
if digit != '3':
return int(s[:i] + '3' + s[i+1:])
return n
# Test the function
print(maximize_number(11332))
print(maximize_number(3333))
print(maximize_number(1221))
31332 3333 3221
Key Points
The algorithm has O(n) time complexity where n is the number of digits
Space complexity is O(n) for storing the digit list
If all digits are already '3', no change is needed
We always change the leftmost non-'3' digit for maximum impact
Conclusion
This greedy approach efficiently finds the maximum number by changing the first non-'3' digit from left to right. The key insight is that changing the leftmost digit has the greatest impact on the final value.
