Largest Odd Number in String (LeetCode 1903): Solution and Explanation

Easy
Math
String
Greedy

Given a large integer as a digit string with no leading zeros, return the largest odd number that appears as a contiguous substring, or an empty string if there is none.

Intuition

Checking every substring would be O(n^2) substrings, each up to n digits long. That is far too slow for 10^5 digits, and the numbers do not fit in any integer type anyway.

Whether a number is odd depends only on its last digit. So an odd substring is any substring that ends on an odd digit, and the question becomes where it should start and where it should end.

For a fixed end position, starting at index 0 gives the most digits. Since num has no leading zeros, a number with more digits is larger, so the best substring ending at position i is the prefix num[:i + 1].

Longer prefixes are larger, so the answer is the prefix ending at the rightmost odd digit. Scan from the right, skip even digits, and stop at the first odd one. If every digit is even, no odd number exists.

Approach: Scan from the right for the last odd digit

  1. Loop i from len(num) - 1 down to 0.
  2. If num[i] is odd, return num[:i + 1].
  3. If the loop finishes, every digit is even, so return "".

Step-by-step example

num = "7438246"
  1. i = 6: digit 6 is even, so no odd number ends here. Move left.
  2. i = 5: digit 4 is even. Move left.
  3. i = 4: digit 2 is even. Move left.
  4. i = 3: digit 8 is even. Move left.
  5. i = 2: digit 3 is odd. Return the prefix num[:3] = "743".

Code: Python, Java, C++

1class Solution:
2    def largestOddNumber(self, num: str) -> str:
3        for i in range(len(num) - 1, -1, -1):
4            if int(num[i]) % 2 == 1:
5                return num[:i + 1]
6        return ""
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

Each digit is checked at most once, and building the returned prefix is also at most n characters.

Space

O(1)

Only the loop index is stored, not counting the returned string.

Other approaches

Check every substring (time O(n^2) comparisons, space O(n))

Enumerate all substrings, keep those ending in an odd digit, and compare them as numbers (by length, then lexicographically). Correct but quadratic in the number of substrings.

Strip trailing even digits (time O(n), space O(n))

Repeatedly drop the last character while it is even, for example with rstrip("02468") in Python. This is the same idea written as a library call.

Common mistakes

  • Converting num to an integer. It can have 10^5 digits, which overflows every fixed-size type and is slow even with big integers.
  • Scanning from the left and stopping at the first odd digit. That returns the shortest odd prefix, not the longest.
  • Returning a single odd digit such as the largest odd digit. A longer number always beats a single digit here.
  • Forgetting the case where every digit is even, which must return an empty string.

Frequently asked questions

Why must the answer start at index 0?

Any substring ending at position i can be extended to the left without changing its last digit, so it stays odd. Extending adds digits, and because num has no leading zero, the extended number is larger.

Could a substring that does not end at the last odd digit be larger?

No. Every odd substring ends at some odd digit at or before the last one, so it has at most as many digits as the prefix through the last odd digit, and that prefix contains it as a smaller piece.

What about zeros inside num?

Zeros are even, so they are only dropped when they sit after the last odd digit. Zeros in the middle stay in the answer, which never starts with a zero because num does not.