Sponsored
If the entire string is considered as a whole number, you only need to check the last digit to determine if it's odd. This is because the entire substring from start to that odd digit will be the largest odd number available. If there is no odd digit, then there's no odd number in the string.
Time Complexity: O(n), where n is the length of the string.
Space Complexity: O(1) because only a constant amount of space is used.
1def largestOddNumber(num: str) -> str:
2 for i in range(len(num) - 1, -1, -1):
3 if int(num[i]) % 2 != 0:
4 return num[:i + 1]
5 return ""
6
7print(largestOddNumber("52"))
8print(largestOddNumber("4206"))
9print(largestOddNumber("35427"))
This Python solution walks backwards through the string, looking for the first odd-numbered character, and returns the full string up to that character if found.
By utilizing regular expressions, find the largest substring ending in any odd digit directly. This will require reversing the string and searching for the first odd digit using a pattern.
Time Complexity: O(n), mainly due to the string reversal and regex search.
Space Complexity: O(n) for the reversed string.
1import re
2
3def largestOddNumber(num:
This solution reverses the string and searches for the first occurrence of an odd digit using a regex pattern. Once found, it calculates the original position and slices the string accordingly.