To solve this problem, we need to find the largest odd number that exists as a prefix of the given numeric string. Let's break it down in simple terms.
We are only allowed to remove digits from the end of the string. That means, we can keep shortening the number from the right side until we find a version that ends with an odd digit.
Case 1: Last digit is odd
If the last digit of the string is odd (like 1, 3, 5, 7, or 9),
{
"array": [1, 2, 3, 4, 5],
"showIndices": false,
"highlightIndicesGreen": [4]
}
then the entire string is already an odd number. We simply return the whole string.
{
"array": [1, 2, 3, 4, 5],
"showIndices": false,
"highlightIndicesGreen": [0,1,2,3,4]
}
Case 2: Last digit is even, but there is an odd digit earlier
If the string ends in an even digit (like 0, 2, 4, 6, 8), we move leftward to find the last occurrence of an odd digit.
{
"array": [1, 2, 3, 4, 6],
"showIndices": false,
"highlightIndicesGreen": [2]
}
The moment we find it, we return the substring from the beginning up to that digit (inclusive). This is the largest odd number that can be formed as a prefix.
{
"array": [1, 2, 3, 4, 6],
"showIndices": false,
"highlightIndicesGreen": [0,1,2]
}
Case 3: No odd digit at all
If the string doesn't contain any odd digits, there is no way to form an odd number.
{
"array": [4, 2, 6, 4, 8],
"showIndices": false,
"highlightIndicesGreen": []
}
In this case, we return an empty string ""
.
Case 4: Edge case - Empty string
If the input is an empty string, we also return ""
since there's nothing to check.
This approach is simple, efficient, and beginner-friendly because we are just scanning the string from the end until we find what we need. There’s no need to convert anything to an actual number or use complex operations.