Understanding the Problem
We are given a numeric string, and we need to find the largest odd number that exists as a prefix of this string.
A prefix means we can only remove digits from the end of the string, not from the beginning or middle.
Our goal is to return the longest prefix that ends in an odd digit (1, 3, 5, 7, 9).
If there's no such prefix, we return an empty string.
Step-by-Step Solution with Example
Step 1: Start from the end of the string
We scan the string from right to left, checking each digit one by one.
The reason we go from the end is because we are only allowed to remove digits from the end. So we’re looking for the last possible point where we can stop trimming.
Step 2: Check if a digit is odd
As we scan each digit, we check whether it is odd.
The first time we find an odd digit, we stop.
We then take the substring from the beginning of the string up to and including this digit.
Step 3: Return the substring
This substring is the largest odd number that can be formed from the original string by removing digits from the end.
Example: Input = "123456"
Let’s walk through this example.
- Start from the end: 6 → even
- Move left: 5 → odd
We found the last odd digit at index 4 (0-based). So, we take the substring from index 0 to 4.
Result: "12345"
Edge Cases
All digits are even
Input: "24680"
There are no odd digits in the string. So, we can’t form any odd number.
Result: ""
Last digit is already odd
Input: "13579"
The last digit is odd, so the entire string is already the largest odd number.
Result: "13579"
Empty string
Input: ""
There is nothing to check, so we return an empty string.
Result: ""
Single odd digit
Input: "7"
It is already an odd number.
Result: "7"
Single even digit
Input: "8"
It is even, and there are no other digits.
Result: ""
Finally
This solution is simple and efficient. We don't need to convert the string into a number or use any advanced operations.
Just a single backward scan of the string is enough.
By checking from the rightmost digit and stopping at the first odd one, we ensure that the result is the longest possible odd prefix.
This method is easy to follow and ideal for beginners learning string manipulation and basic conditions.
Comments
Loading comments...