Valid Number (LeetCode 65): Solution and Explanation

Hard
String

Decide whether a string is a number of the form [sign] digits [. digits] [e [sign] digits], where the mantissa needs at least one digit on some side of the dot and the exponent needs its own digits. "0" is valid, "e" and "." are not.

Intuition

The grammar looks long, but every character type has exactly one rule about where it may stand. A digit can go anywhere. A sign can only open the number or open the exponent. A dot can appear once, and only before the exponent. An e can appear once, and only after some digits.

So you never need to backtrack. Read left to right and remember three facts: whether the current part has a digit yet, whether a dot has appeared, and whether an exponent has started.

When e arrives, the mantissa is finished and the exponent is a fresh integer, so reset the digit flag. At the end the string is valid exactly when the last part has at least one digit.

Approach: Single scan with three flags

  1. Set seenDigit, seenDot and seenExp to false.
  2. Digit: set seenDigit.
  3. Sign: valid only at index 0 or right after e/E; otherwise return false.
  4. e or E: return false if an exponent was already seen or no digit came before it. Otherwise set seenExp and reset seenDigit.
  5. Dot: return false if a dot or an exponent was already seen. Otherwise set seenDot.
  6. Any other character: return false.
  7. After the loop, return seenDigit.

Step-by-step example

s = "0"
  1. All three flags start false.
  2. Read 0. It is a digit, so it fills the integer part and seenDigit becomes true.
  3. The string ends. The last part (the integer) has a digit, so the answer is true.
  4. Compare "e": the first character is e but seenDigit is false, so it fails at once. And ".": the dot is accepted, but the scan ends with seenDigit false, so the answer is false.

Code: Python, Java, C++

1class Solution:
2    def isNumber(self, s: str) -> bool:
3        seen_digit = seen_dot = seen_exp = False
4        for i, ch in enumerate(s):
5            if '0' <= ch <= '9':
6                seen_digit = True
7            elif ch in '+-':
8                if i > 0 and s[i - 1] not in 'eE':
9                    return False
10            elif ch in 'eE':
11                if seen_exp or not seen_digit:
12                    return False
13                seen_exp = True
14                seen_digit = False
15            elif ch == '.':
16                if seen_dot or seen_exp:
17                    return False
18                seen_dot = True
19            else:
20                return False
21        return seen_digit
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

Each character is examined once with constant work.

Space

O(1)

Only three boolean flags and a loop index.

Other approaches

Deterministic finite automaton (time O(n), space O(1))

Model the grammar as about nine states (start, sign, integer, dot after digits, dot first, fraction, exponent, exponent sign, exponent digits) with a transition table keyed by character class. Accept if the final state is one of the accepting ones. Same complexity, more code, but very systematic.

Regular expression (time O(n), space O(1))

Match ^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$. Short and correct, though interviewers usually want the hand-written scan.

Language number parser (time O(n), space O(1))

Calling float() or Double.parseDouble is tempting but wrong: they accept strings such as inf, nan, 1_000 or trailing f/d suffixes that this problem rejects.

Common mistakes

  • Forgetting to reset the digit flag at e. Without it, "1e" would be accepted because a digit was seen earlier.
  • Allowing a sign anywhere. "6+1" and "-+3" are invalid: a sign must be first or come right after e.
  • Rejecting "4." or ".5". A dot is fine with digits on only one side; only a lone "." (no digits at all) is invalid.
  • Allowing a dot inside the exponent, as in "99e2.5". The exponent must be an integer.

Frequently asked questions

Why is "4." valid but "." not?

A decimal needs at least one digit, on either side of the dot. "4." has a digit before the dot. "." has none, so the final seenDigit check fails.

Why reset seenDigit when the exponent starts?

The exponent is a separate integer that needs its own digits. Resetting the flag makes the final check ask whether the exponent has digits, which rejects "1e" and "1e+".

Is the finite automaton solution better?

It is equivalent. The three flags are a compressed form of the automaton's state. The automaton is easier to extend if the grammar grows, while the flag version is shorter to write in an interview.