Largest Odd Number in String

Largest odd-valued substring of a digit string — scan from the right for the first odd digit.

Easy
Time O(n) Space O(1)
LeetCode
2 min read
greedy string

Problem#

Return the largest odd-valued substring of num, or "" if none exists.

Examples#

  • "52""5"
  • "4206"""
  • "35427""35427"

Constraints#

  • 1 <= num.length <= 10^5.

Approach#

Scan from right; first odd digit found is the suffix-end of the answer. Return num.substr(0, lastOddIndex + 1).

Solution#

Largest Odd Number in String
class Solution {
public:
string largestOddNumber(string num) {
for (int i = num.size() - 1; i >= 0; --i) {
if ((num[i] - '0') % 2 == 1) return num.substr(0, i + 1);
}
return "";
}
};

Editorial#

A number is odd iff its last digit is odd. The largest-magnitude odd substring keeps as many leading digits as possible — so we want the rightmost odd digit, and everything before it.

Complexity#

  • Time: O(n).
  • Space: O(1).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.