AlgoViz

Largest Odd Number in a String

Easy

Scan back to the last odd digit

Problem

Given a numeric string, return the largest odd-valued number that is a non-empty prefix (substring from the start).

In simple words

The biggest odd number is the longest prefix that ends on an odd digit.

The idea

The answer must be a prefix, and a number is odd exactly when its last digit is odd. So walk backwards to the rightmost odd digit and return everything up to and including it — the longest prefix beats any shorter one.

The trick

  • Longest valid prefix wins, so scan from the right and stop at the first odd digit.
  • Return an empty string when every digit is even.
  • O(n), no big-number arithmetic needed.

This one walks through the worked example rather than tracing the algorithm frame by frame — a full walkthrough is still to be drawn. The code and the idea below are the real solution.

52
0

Step 1 of 2. Here's the example — '52' Values: 52.

1/2
Optimal
timeO(n)spaceO(1)
1for i from n-1 to 0:2  if s[i] is odd: return s[0..i]3return ''

Input

array
[52]

Output

answer

Check yourself

3 quick questions about this walkthrough. A wrong answer costs nothing.

Examples

Example 1

Input:
s = "52"
Output:
"5"
Explanation:
Trim to the last odd digit: 5.

Example 2

Input:
s = "4206"
Output:
""
Explanation:
No odd digit anywhere → empty string.

Example 3

Input:
s = "35427"
Output:
"35427"
Explanation:
The whole string already ends in an odd digit.

Finished the walkthrough? Add it to your streak.