Largest Odd Number in String - Problem
You're given a string num representing a large integer. Your task is to find the largest-valued odd number that exists as a substring within this number.
๐ฏ Goal: Return the largest odd integer (as a string) that is a contiguous substring of num. If no odd number exists, return an empty string "".
Key Points:
- A number is odd if its last digit is 1, 3, 5, 7, or 9
- A substring must be contiguous characters from the original string
- We want the largest possible value, not the longest substring
Example: In "52", we have substrings: "5", "2", "52". Only "5" is odd, so we return "5".
Input & Output
example_1.py โ Basic Case
$
Input:
num = "52"
โบ
Output:
"5"
๐ก Note:
The substrings are "5", "2", and "52". Among these, "5" and "52" could be candidates, but "52" is even (ends in 2), so only "5" is odd. Therefore, "5" is the largest odd number.
example_2.py โ Multiple Odd Digits
$
Input:
num = "4206"
โบ
Output:
""
๐ก Note:
All digits (4, 2, 0, 6) are even, so no substring can form an odd number. We return an empty string.
example_3.py โ Optimal Substring
$
Input:
num = "35427"
โบ
Output:
"35427"
๐ก Note:
The entire string ends with 7 (odd), so "35427" is the largest possible odd number. Any smaller substring starting from index 0 would be smaller in value.
Constraints
- 1 โค num.length โค 105
- num consists of only digits
- No leading zeros in the input string
- num represents a valid integer
Visualization
Tap to expand
Understanding the Visualization
1
Understand the Goal
We want the largest-valued odd number, which means it should be as long as possible while ending in an odd digit
2
Key Insight
The largest odd number will always start from index 0 (to maximize value) and end at the rightmost odd digit
3
Scan Strategy
Start from the right and find the first odd digit, then return the prefix from start to that position
Key Takeaway
๐ฏ Key Insight: The largest odd number will always be the prefix ending at the rightmost odd digit, making this a perfect greedy problem!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code