Problem Description
Given a string representing a large integer, return the largest-valued odd integer (as a string) that is a contiguous substring of the input string. If no odd digit exists in the string, return an empty string.
Key Insights
- The largest odd integer, in value, can be obtained by using as many digits from the start as possible until the last odd digit.
- Traversing the string from right to left to find the last occurrence of an odd digit ensures keeping the most significant digits intact.
- If no odd digit is encountered, the result should be an empty string.
Space and Time Complexity
Time Complexity: O(n), where n is the length of the string (single reverse scan).
Space Complexity: O(n) in the worst case for the substring output, with O(1) additional space.
Solution
The solution involves scanning the given number string from right to left, searching for the first odd digit encountered. Once an odd digit is found, the substring from the beginning of the string up to that digit (inclusive) is returned. This guarantees the largest odd number since removing any digits from the left would result in a smaller number, and using any substring not starting from the beginning would omit critical digits. If no odd digit is found, the function returns an empty string.