1903. Largest Odd Number in String LeetCode Solution

In this guide, you will get 1903. Largest Odd Number in String LeetCode Solution with the best time and space complexity. The solution to Largest Odd Number in String problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Largest Odd Number in String solution in C++
  4. Largest Odd Number in String solution in Java
  5. Largest Odd Number in String solution in Python
  6. Additional Resources
1903. Largest Odd Number in String LeetCode Solution image

Problem Statement of Largest Odd Number in String

You are given a string num, representing a large integer. Return the largest-valued odd integer (as a string) that is a non-empty substring of num, or an empty string “” if no odd integer exists.
A substring is a contiguous sequence of characters within a string.

Example 1:

Input: num = “52”
Output: “5”
Explanation: The only non-empty substrings are “5”, “2”, and “52”. “5” is the only odd number.

Example 2:

Input: num = “4206”
Output: “”
Explanation: There are no odd numbers in “4206”.

Example 3:

Input: num = “35427”
Output: “35427”
Explanation: “35427” is already an odd number.

Constraints:

1 <= num.length <= 105
num only consists of digits and does not contain any leading zeros.

Complexity Analysis

  • Time Complexity: O(n)
  • Space Complexity: O(n)

1903. Largest Odd Number in String LeetCode Solution in C++

class Solution {
 public:
  string largestOddNumber(string num) {
    for (int i = num.length() - 1; i >= 0; --i)
      if ((num[i] - '0') % 2 == 1)
        return num.substr(0, i + 1);
    return "";
  }
};
/* code provided by PROGIEZ */

1903. Largest Odd Number in String LeetCode Solution in Java

class Solution {
  public String largestOddNumber(String num) {
    for (int i = num.length() - 1; i >= 0; --i)
      if ((num.charAt(i) - '0') % 2 == 1)
        return num.substring(0, i + 1);
    return "";
  }
}
// code provided by PROGIEZ

1903. Largest Odd Number in String LeetCode Solution in Python

class Solution:
  def largestOddNumber(self, num: str) -> str:
    for i, n in reversed(list(enumerate(num))):
      if int(n) % 2 == 1:
        return num[:i + 1]
    return ''
# code by PROGIEZ

Additional Resources

See also  1606. Find Servers That Handled Most Number of Requests LeetCode Solution

Happy Coding! Keep following PROGIEZ for more updates and solutions.