⬅ Previous Topic
Reverse Words in a StringNext Topic ⮕
Find Longest Common Prefix in Array of Strings⬅ Previous Topic
Reverse Words in a StringNext Topic ⮕
Find Longest Common Prefix in Array of StringsTopic Contents
Given a numeric string (i.e., a string that contains only digits), your task is to extract the largest-valued odd number that can be formed by removing some digits from the end of the string.
empty string ""
.Remember, a number is odd if it ends with 1, 3, 5, 7,
or 9
.
""
.def largest_odd_number(num):
for i in range(len(num) - 1, -1, -1):
if int(num[i]) % 2 == 1:
return num[:i + 1] # Return the substring ending at the last odd digit
return "" # No odd digit found
# Sample Input
print(largest_odd_number("4206")) # Output: ""
Case | Time Complexity | Explanation |
---|---|---|
Best Case | O(1) | If the last character is odd, we return immediately. |
Average Case | O(n) | In the average case, we might scan most of the string to find the last odd digit. |
Average Case | O(n) | If no odd digit is present, the entire string is scanned once. |
O(1)
Explanation: We use a constant number of variables, and only return a substring from the original input.
⬅ Previous Topic
Reverse Words in a StringNext Topic ⮕
Find Longest Common Prefix in Array of StringsYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.