Largest Odd Number in String
Pattern: Strings basics and frequency
A number is odd when its last digit is odd, and among substrings the longest prefix is the biggest. So find the last odd digit and return everything up to it.
The problem
You are given a string of digits, num, with no leading zeros. Return the largest odd number that is a non-empty
substring of num, as a string, or an empty string if there is none. For example, "52" gives "5", "4206" gives
"", and "35427" gives "35427".
The function name largestOddNumber matches LeetCode. Use the link above for the exact statement and limits.
Think first
- Which digit decides whether a number is odd?
- Among substrings that are odd numbers, which one is the largest?
- Can a substring that does not start at index 0 ever beat the best prefix?
Hints
Brute force, and why it fails
Try every substring, keep the odd ones and compare them as numbers: O(n³) with string comparisons, and they can be too long for any number type. The rightmost odd digit gives the answer in one scan.
The key insight
Two facts combine: oddness depends only on the last digit, and the longest prefix is the biggest number. So the answer is decided by one position, the last odd digit.
Dry run
num = 35427. Scan from the right, looking for an odd digit.
The plan
for i from n - 1 down to 0:
if digit s[i] is odd: return s[0 .. i]
return ""
Complexity
- Time
O(n)- Space
O(1)
One scan from the right. The returned substring is the output.
Edge cases
- All digits even:
"". - Last digit odd: the whole string.
- Very long strings: never convert to a number, it would overflow.
I've built my logic, show the code
Java
class Solution {
public String largestOddNumber(String num) {
for (int i = num.length() - 1; i >= 0; i--) {
if ((num.charAt(i) - '0') % 2 == 1) return num.substring(0, i + 1); // longest prefix ending in odd
}
return "";
}
}C++
class Solution {
public:
string largestOddNumber(string num) {
for (int i = static_cast<int>(num.size()) - 1; i >= 0; i--) {
if ((num[i] - '0') % 2 == 1) return num.substr(0, i + 1); // longest prefix ending in an odd digit
}
return "";
}
};Python
class Solution:
def largestOddNumber(self, num: str) -> str:
for i in range(len(num) - 1, -1, -1):
if int(num[i]) % 2 == 1:
return num[:i + 1] # longest prefix ending in an odd digit
return ""Common mistakes
- Converting the string to an integer, which overflows for long inputs.
- Returning the single odd digit instead of the prefix ending at it.
- Scanning from the left and returning the first odd digit.