#1903
Largest Odd Number in String
EasyMathStringGreedyGreedyString Manipulation
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
Instead of generating all substrings, we can directly look for the last odd digit in the string. The largest odd number will always be the substring from the start of the string to this last odd digit.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a variable to store the result as an empty string.
- 2Step 2: Iterate through the string from the end to the beginning.
- 3Step 3: If an odd digit is found, set the result to the substring from the start to this digit and break the loop.
solution.py7 lines
1num = '35427'
2result = ''
3for i in range(len(num) - 1, -1, -1):
4 if int(num[i]) % 2 == 1:
5 result = num[:i + 1]
6 break
7print(result)ℹ
Complexity note: This complexity is linear because we only traverse the string once, looking for the last odd digit.
- 1The largest odd number can be determined by the last odd digit in the string.
- 2We can avoid unnecessary checks by iterating from the end of the string.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.