VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-the-largest-odd-number-in-string/

⇱ Largest odd number in a String - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Largest odd number in a String

Last Updated : 3 Jun, 2026

Given a string s, representing a non-negative integer, return the largest-valued odd integer (as a string) that is a substring of the given string s. If no such odd-valued substring exists, return an empty string ("").

Examples:

Input: s = "504"
Output: "5"
Explanation: The only substring "5" is an odd number.

Input: s = "2042"
Output: ""
Explanation: All the possible non-empty substrings have even values.

[Naive Approach] Check All Substrings for Odd Value - O(|s|^3) Time and O(1) Space

The idea is to generate all possible substrings of the given string and check whether each substring represents an odd number. A number is odd if its last digit is odd. Among all valid substrings, we keep the maximum-valued one.


Output
5

[Expected Approach] Greedy Right-to-Left Scan - O(|s|) Time and O(1) Space

The key idea is that a number is odd only if its last digit is odd (1, 3, 5, 7, 9). Therefore, to obtain the largest-valued odd substring, we find the rightmost odd digit in the string and return the prefix of the string ending at that index.

  • Traverse the string from right to left.
  • Check each digit if it is odd.
  • If an odd digit is found at index i, return s[0...i].
  • If no odd digit is found, return an empty string.

Consider string : s = "504"

Step 1: Traverse the string from index n-1 to 0 to find the first odd digit.

Step 2: Check characters

  • i = 2 -> S[i] = '4' -> even -> continue
  • i = 1 -> S[i] = '0' -> even -> continue
  • i = 0 -> S[i] = '5' -> odd -> stop

Step 3: First odd digit is found at index 0, so we return: S[0...0] = "5"


Output
5
Comment
Article Tags:
Article Tags: