EasyNo. 1903

Largest Odd Number in String — LeetCode 1903 Python Solution

Pattern
Greedy
Topics
Greedy, Math, String
Reading time
2 min

The problem

You are given a string num, representing a large integer. Return the largest-valued odd integer (as a string) that is a non-empty substring of num, or an empty string "" if no odd integer exists.

Example

Input
num = "52"
Output
"5"
Explanation
The only non-empty substrings are "5", "2", and "52". "5" is the only odd number.

Python solution

PythonSolution
class Solution:
    def largestOddNumber(self, num: str) -> str:
        for i in range(len(num) - 1, -1, -1):
            if (int(num[i]) & 1) == 1:
                return num[: i + 1]
        return ''

Complexity

Time
O(n)where n is the length of the string num
Space · auxiliary
O(1)

Pattern: Greedy

Take the locally best option every time — when you can prove that never costs you later. LeetCode 1903. Largest Odd Number in String is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Greedy.

The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1903. Largest Odd Number in String?

LeetCode 1903. Largest Odd Number in String is rated Easy on LeetCode.

What is the time complexity of LeetCode 1903. Largest Odd Number in String?

The Python solution on this page runs in O(n), where n is the length of the string num.

What is the space complexity of LeetCode 1903. Largest Odd Number in String?

The Python solution on this page uses O(1) auxiliary space.

What topics does LeetCode 1903. Largest Odd Number in String cover?

LeetCode 1903. Largest Odd Number in String is tagged Greedy, Math and String on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.