Find the largest odd number that is a substring of a string of digits.
Problem Statement
Examples
Input: num = "52"
Output: "5"
Explanation: "5" is the largest odd substring in "52".
Input: num = "4206"
Output: ""
Explanation: No odd digit exists in "4206", so the output is an empty string.
Input: num = "35427"
Output: "35427"
Explanation: "35427" is the largest odd substring in "35427".
Complexity
Time Complexity: O(N)
Space Complexity: O(1)
Hints
Editorial & Approach
Problem Overview & Intuition
Any substring starting at index 0 and ending at index i represents a valid prefix. Since larger values correspond to longer prefixes, the largest odd number is simply the prefix ending at the rightmost odd digit.
Step-by-Step Approach
- Iterate
ibackwards fromnum.length - 1down to0. - Check if
parseInt(num[i]) % 2 !== 0. - If odd, return
num.substring(0, i + 1). - If no odd digit is found, return
"".
Optimal Implementation (JavaScript)
function largestOddNumber(num) {
for (let i = num.length - 1; i >= 0; i--) {
if (parseInt(num[i]) % 2 !== 0) {
return num.substring(0, i + 1);
}
}
return "";
}
Complexity Analysis
Edge Cases & Corner Traps Handled
- No odd digits: "4206" -> "".
- Last digit is odd: entire string returned.
- Only first digit is odd: "52" -> "5".