Problem 1903

Abstract / Summary

Find the biggest odd number that can be made from the digits in the given string.

Note

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

Python 1903.py

class Solution:
    def largestOddNumber(self, num: str) -> str:
        while num and num[-1] not in "13579":
            num = num[:-1]
        return num
5 lines | 162 bytes | submitted December 9, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 65% (600k+ submissions).

Typical patterns to solve this problem:
  • Greedy
  • Math
  • String
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 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 num is an empty string, the loop condition num evaluates 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 num consists 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.

written by openai gpt

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.

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 = 8 | μ = 8.19 | σ = 0.98

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 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
27 links | 15 authors | 8 languages

Videos

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

Similar Problems

2 similar problems

Solved On The Same Day

4 solutions   December 9, 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