Given a string of digits, The task is to find the largest odd number that can be represented by a substring of the given string, return an empty string if no substring can represent an odd number.
Examples :
Input : Str = "123456" Output : "12345" Explanation : Str[0, 4] corresponds to "12345" which is the largest valued odd number that can be formed from the given string. Input : Str = "86048" Output : "" Explanation : There is no substring in the given string that corresponds to an odd integer number.
Approach :
We know that for a number to be odd its last digit should not be even and to find the largest valued odd number, We can simply choose the longest substring whose last digit is odd. Follow the steps below to solve the problem:
- maintain a variable say i, that points to the last index of the string.
- Traverse the string from behind and perform the following steps.
- if the current digit is an even number move to the next character.
- if the current digit is an odd number, we have found the required substring that is Str[0,i]
- After completing the above steps if we have not found the required substring we can conclude that an odd number can not be formed.
Implementation :
//C++ program for the above approach.
#include <iostream>
using namespace std;
//Function to return the largest
//odd number represented as a string
string largestOdd(string s)
{
int n = s.length();
//i points to last digit of string
int i = n - 1;
//traverse from the back
for(i; i >= 0; i--)
{
if((s[i] - '0') % 2)
{
//since s[i] is an odd digit
//we have found the required answer.
return s.substr(0, i + 1);
}
}
//if no substring represents an odd number.
return "";
}
//Driver Code
int main()
{
string str = "432148";
cout << largestOdd(str) << endl;
return 0;
}
Output :
4321
Time Complexity : O(N)
Auxiliary Space : O(1)