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
Why the Greedy Approach WorksExample: "52301"52301Rightmost odd digit at index 4All Possible Odd Substrings:5Value: 5523Value: 52352301Value: 52301 โ† LARGEST!3Value: 31Value: 1๐Ÿง  Key Insight:โ€ข The largest odd number starting from index 0 will end at the RIGHTMOST odd digitโ€ข Any substring ending at an earlier odd digit will have smaller valueโ€ข We can find this in O(n) time by scanning from right to leftAlgorithm Visualization:1Start from rightmost position2Move left until you find an odd digit (1,3,5,7,9)3Return substring from start to that position
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!
Asked in
Amazon 45 Google 32 Microsoft 28 Meta 22
52.0K Views
Medium Frequency
~15 min Avg. Time
2.2K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen