Problem 1323

Abstract / Summary

Given a number, change at most one digit 6 to 9 to get the largest possible value.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1323.py

class Solution:
    def maximum69Number (self, num: int) -> int:
        return int(str(num).replace("6", "9", 1))
3 lines | 118 bytes | submitted November 28, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 85% (500k+ submissions).

Typical patterns to solve this problem:
  • Greedy
  • Math
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a Solution class with a single method, maximum69Number. The method receives an integer, transforms it into a string, substitutes the first occurrence of the digit 6 with 9, and finally converts the modified string back to an integer. This approach directly leverages Python’s built-in string handling capabilities to achieve the desired transformation in a concise manner.

Key Steps

The algorithm can be broken down into three logical operations, each reflected by a distinct line of code.

Converting the integer to a string

str(num)

The input integer num is cast to its textual representation. This step enables character-level manipulation, which is essential for locating and replacing specific digits.

Replacing the first ‘6’ with ‘9’

.replace("6", "9", 1)

The replace method is invoked on the string obtained from the previous step. By specifying a count of 1, only the earliest occurrence of the character '6' is altered to '9'. If the string contains no '6', the method leaves it unchanged, thereby preserving the original value.

Converting the result back to an integer

int(...)

After the substitution, the modified string is wrapped with int() to produce the final numeric result expected by the caller.

Edge Cases Handled

When the input number does not contain any digit 6, the replace call performs no modification, and the integer returned is identical to the input. This behavior naturally covers numbers composed solely of digits 9, 0, or any other digit besides 6.

If the number consists of a single digit 6, the conversion yields the string "6", the replacement changes it to "9", and the final integer becomes 9.

For numbers that contain multiple 6 digits, only the leftmost (most significant) 6 is upgraded to 9, while subsequent 6 characters remain untouched. This aligns with the requirement to maximize the resulting value by altering at most one digit.

The method also gracefully processes numbers where the leading digit is 6, ensuring that the most significant position is considered first, which yields the greatest possible increase in magnitude.

Performance Optimizations

The implementation relies on Python’s highly optimized C-level string operations. The replace function with a limit of one replacement avoids scanning the entire string more than necessary; it stops after the first match, reducing unnecessary work for long inputs that contain an early 6.

By performing the conversion to a string only once and converting back to an integer a single time, the code minimizes the overhead associated with type casting. No auxiliary data structures are created, and the memory footprint remains minimal throughout execution.

Overall, the solution achieves the transformation with a straightforward, low-overhead sequence of built-in operations, making it both succinct and efficient for the intended problem scope.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a magic box that holds a number made of sixes and nines. This special box wants to make the number as big as it possibly can. To do this, the box first looks at the number like it is a string of tiny wooden blocks sitting in a row. It starts checking each block from the left side. As soon as it spots the very first number six, it swaps that six for a nine. Because nine is bigger than six, the whole number suddenly grows to be the largest one it can be. Once that one swap happens, the box stops looking and puts the new number back together for you to see.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 9 | μ = 8.67 | σ = 1.19

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Java Python TS
WalkCCC C++ Java Python
leetcode.ca C++ Java Python C Go PHP Rust TS
Progiez C++ Java Python
github BigEggStudy C#
black-shadows C++
chandansgowda Python
charles-wangkai Java
DimitrisJim C
everthis JS
fartem Ruby
fsq C++
JoshCrozier JS
keineahnung2345 C++
Krazune C++
lkwq007 Python
lzl124631x C++
qiyuangong Java
suxrobGM C#
varunu28 Java
vthwang Java
YuriSpiridonov Python
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C, C++, Go, Java, PHP, Python, Rust, TypeScript
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
chandansgowda Python
charles-wangkai Java
DimitrisJim C
everthis JavaScript
fartem Ruby
fsq C++
JoshCrozier JavaScript
keineahnung2345 C++
Krazune C++
lkwq007 Python
lzl124631x C++
qiyuangong Java
suxrobGM C#
varunu28 Java
vthwang Java
YuriSpiridonov Python
36 links | 22 authors | 11 languages

Videos

7 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

10 solutions   November 28, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality