Largest Odd Number in String - 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.

A substring is a contiguous sequence of characters within a string.

Input & Output

Example 1 — Basic Case with Odd Ending
$ Input: num = "52301"
Output: "52301"
💡 Note: The entire string ends with '1' which is odd, so "52301" is the largest odd substring.
Example 2 — Even Ending, Find Rightmost Odd
$ Input: num = "5234"
Output: "523"
💡 Note: The string ends with '4' (even), but '3' at position 2 is the rightmost odd digit, so we take "523".
Example 3 — No Odd Digits
$ Input: num = "246"
Output: ""
💡 Note: All digits are even (2, 4, 6), so no odd substring exists. Return empty string.

Constraints

  • 1 ≤ num.length ≤ 105
  • num consists of only digits

Visualization

Tap to expand
Largest Odd Number in String INPUT String: num = "52301" 5 idx 0 2 idx 1 3 idx 2 0 idx 3 1 idx 4 Odd digits: 1, 3, 5, 7, 9 Even digits: 0, 2, 4, 6, 8 O E O E O O = Odd, E = Even ALGORITHM STEPS 1 Start from right end Scan from index n-1 to 0 2 Check if digit is odd digit % 2 == 1 ? 3 Found odd? Return! Return substring [0...i] 4 No odd found Return empty string "" Trace for "52301": i=4: '1' is odd FOUND! Return num[0:5] --> "52301" FINAL RESULT Rightmost odd digit at index 4 5 2 3 0 1 Rightmost odd digit Output: "52301" OK - Complete! Entire string is the answer (ends with odd digit 1) Key Insight: A number is odd if and only if its last digit is odd. To find the largest odd substring, we scan from right to left and return everything from the start up to the first odd digit found. This greedy approach works in O(n) time with O(1) extra space. TutorialsPoint - Largest Odd Number in String | Greedy - Find Rightmost Odd Digit
Asked in
Google 25 Amazon 20 Microsoft 15
25.0K Views
Medium Frequency
~15 min Avg. Time
890 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