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.
For example:
num = "52"
, the output should be "5"
. The non-empty substrings are "5", "2", and "52". "5" is the only odd number.num = "4206"
, the output should be ""
. There are no odd numbers in "4206".num = "35427"
, the output should be "35427"
. "35427" is already an odd number.Write an efficient algorithm to solve this problem. What is the time and space complexity of your solution? Can you handle very large numbers efficiently? What edge cases should you consider?
Let's explore different approaches to solve the problem of finding the largest odd substring.
We can generate all possible substrings of the given string num
and check each substring to see if it represents an odd number. We keep track of the largest odd substring found so far.
Code (Python):
def largestOddSubstring_naive(num):
largest_odd = ""
for i in range(len(num)):
for j in range(i, len(num)):
sub = num[i:j+1]
if int(sub) % 2 != 0:
if len(sub) > len(largest_odd):
largest_odd = sub
elif len(sub) == len(largest_odd) and sub > largest_odd:
largest_odd = sub
return largest_odd
Time Complexity: O(n^3), where n is the length of the input string. Generating all substrings takes O(n^2) time, and checking if each substring is odd and comparing it with the current largest odd substring takes O(n) time in the worst case.
Space Complexity: O(n), where n is the length of the input string, to store the largest odd substring.
Instead of generating all substrings, we can iterate through the string from right to left. If we find an odd digit, we can simply return the substring from the beginning of the string up to and including that odd digit. This works because we're looking for the largest odd substring. If we find an odd digit towards the end of the number, any substring ending with that digit will be larger than any substring ending with an odd digit earlier in the number.
Code (Python):
def largestOddSubstring(num):
for i in range(len(num) - 1, -1, -1):
if int(num[i]) % 2 != 0:
return num[:i+1]
return ""
Time Complexity: O(n), where n is the length of the input string. In the worst case, we iterate through the entire string.
Space Complexity: O(1). We only use a constant amount of extra space.