Sponsored
If the entire string is considered as a whole number, you only need to check the last digit to determine if it's odd. This is because the entire substring from start to that odd digit will be the largest odd number available. If there is no odd digit, then there's no odd number in the string.
Time Complexity: O(n), where n is the length of the string.
Space Complexity: O(1) because only a constant amount of space is used.
1public class LargestOddNumber {
2 public static String largestOddNumber(String num) {
3 for (int i = num.length() - 1; i >= 0; i--) {
4 if ((num.charAt(i) - '0') % 2 != 0) {
5 return num.substring(0, i + 1);
6 }
7 }
8 return "";
9 }
10
11 public static void main(String[] args) {
12 System.out.println(largestOddNumber("52"));
13 System.out.println(largestOddNumber("4206"));
14 System.out.println(largestOddNumber("35427"));
15 }
16}
Implemented in Java, this solution checks each character starting from the end of the input string for an odd digit and returns the largest possible substring formed until that character.
By utilizing regular expressions, find the largest substring ending in any odd digit directly. This will require reversing the string and searching for the first odd digit using a pattern.
Time Complexity: O(n), mainly due to the string reversal and regex search.
Space Complexity: O(n) for the reversed string.
1function largestOddNumber(num) {
2 const reversedNum =
JavaScript's approach uses regex to find the first odd digit after reversing the number. Then, it calculates the original index and slices the string from the start to that point.