Python 1903.py
class Solution:
def largestOddNumber(self, num: str) -> str:
while num and num[-1] not in "13579":
num = num[:-1]
return num
Difficulty
and has an acceptance rate of about 65% (600k+ submissions).
Typical patterns to solve this problem:
- Greedy
- Math
- String
AI Disclaimer
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.
Code Walkthrough
Overview
The provided implementation defines a class Solution with a single method largestOddNumber. The method receives a numeric string num and returns the longest prefix of that string that ends with an odd digit. If the original string already ends with an odd digit, it is returned unchanged; otherwise trailing even digits are stripped until an odd digit is encountered or the string becomes empty.
Core Logic
The essential operation is a loop that examines the last character of the string and removes it when the character is not one of the odd digits "1", "3", "5", "7", "9".
while num and num[-1] not in "13579":
num = num[:-1]
The loop condition checks two things: that the string is non-empty and that its final character is not odd. Inside the loop, slicing num[:-1] creates a new string that excludes the last character. When the loop terminates, num either ends with an odd digit or is empty, and the method returns this result.
return num
Edge Cases Handled
The code gracefully handles several boundary conditions:
- Empty Input - If
numis an empty string, the loop conditionnumevaluates to false immediately, and the method returns the empty string without error. - All Even Digits - For inputs such as
"24680"the loop repeatedly removes each character until the string becomes empty, resulting in an empty return value, which correctly represents the absence of any odd-ending prefix. - Single-Character Input - When
numconsists of a single digit, the loop either skips removal (if the digit is odd) or removes the sole character (if the digit is even), yielding the appropriate result. - Leading Zeros - The algorithm does not alter leading zeros because it only trims from the right side. A string like
"0042"becomes"004"after removal of the trailing even digit, preserving the original leading zeros.
Performance Considerations
The implementation leverages Python’s string slicing, which creates a new string each iteration. Because each iteration discards exactly one character, the total number of slice operations is bounded by the length of the original string. This linear progression ensures that the method finishes after at most one pass over the characters from the end toward the beginning.
The use of the membership test not in "13579" is efficient; the constant string "13579" is small, allowing the interpreter to perform the check quickly without additional data structures. The loop terminates as soon as an odd digit is found, avoiding unnecessary work when the input already ends with an odd digit.
Overall, the method provides a concise solution that directly addresses the problem with minimal overhead, relying on native string operations that are well-optimized in the Python runtime.
ELI5 - Simplified Explanation
Think of the code as a machine that looks at a long string of numbers, just like a line of train cars. The goal is to find the biggest odd number hidden inside that long chain. An odd number is special because it always ends with a one, a three, a five, a seven, or a nine.
The machine starts by looking at the very last train car at the end of the line. If that last car is not one of those special odd numbers, the machine decides that it does not want that car, so it simply unhooks it and tosses it away. Then, the machine looks at the new last car and checks it again. It keeps unhooking and removing cars one by one from the end until it finally finds a car that is an odd number. As soon as it sees an odd number at the very end, it stops working because the biggest odd number has been found.
Code Quality
Complexity Analysis
Other Solutions
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 | Python | C++ | Java | TS | ||||
| WalkCCC | Python | C++ | Java | ||||||
| leetcode.ca | Python | C++ | JS | Java | Go | TS | |||
| Progiez | Python | C++ | Java | ||||||
| github | black-shadows | C++ | |||||||
| charles-wangkai | Java | ||||||||
| everthis | JS | ||||||||
| fartem | Ruby | ||||||||
| fsq | C++ | ||||||||
| JoshCrozier | JS | ||||||||
| lkwq007 | Python | ||||||||
| pruthvikp | Python | ||||||||
| suxrobGM | C# | ||||||||
| trung-hn | Python | ||||||||
| varunu28 | Java | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Python, Java | ||||||||
| leetcode.ca | C++, Go, Java, JavaScript, Python, TypeScript | ||||||||
| Progiez | C++, Java, Python | ||||||||
| black-shadows | C++, C++ | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JavaScript | ||||||||
| fartem | Ruby | ||||||||
| fsq | C++ | ||||||||
| JoshCrozier | JavaScript | ||||||||
| lkwq007 | Python | ||||||||
| pruthvikp | Python | ||||||||
| suxrobGM | C# | ||||||||
| trung-hn | Python | ||||||||
| varunu28 | Java |
Videos
Similar Problems
- problem 2098: Subsequence of Size K With the Largest Even Sum
- problem 2264: Largest 3-Same-Digit Number in String
Solved On The Same Day
- problem 2011: Final Value of Variable After Performing Operations
- problem 2769: Find the Maximum Achievable Number
- problem 2942: Find Words Containing Character
Extra
- 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