Largest Odd Number in String — LeetCode 1903 Python Solution
- Problem
- #1903
- Pattern
- Greedy
- Reading time
- 2 min
- Source
- leetcode.com
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
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
| Measure | Complexity |
|---|---|
| Time | O(n), where n is the length of the string num |
| Space | O(1) auxiliary |
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.