Valid Number

Hard

Topics
String

Given a string s, return true if s is a valid number. A valid number has an optional sign, an integer or decimal part with at least one digit, and an optional exponent (e or E) followed by an optional sign and at least one digit.

Example 1

0
The grammar is small but every clause earns its place: an optional sign, then digits with an optional decimal point (a point needs digits on at least one side), then an optional exponent whose own digits are mandatory and must be integers. A state machine makes the clauses explicit; a regex states them in one line. This one satisfies every clause.
Cells are the characters of the string; the small numbers underneath are indices.
Input:  s = "0"
Output: true

Example 2

e
This one breaks a clause, so it is rejected.
Input:  s = "e"
Output: false

Example 3

-90E3
Input:  s = "-90E3"
Output: true

Constraints

  • 1 <= s.length <= 12
  • s consists of digits, '+', '-', '.', 'e', 'E'.
Editorial — intuition, approach, complexity and pitfalls

Intuition

The grammar is small enough to parse in one left-to-right pass, and writing it as a scan rather than a pile of conditionals is what keeps it correct: an optional sign, then a mantissa, then an optional exponent, then end of input.

The mantissa rule is the one people get wrong. It needs at least one digit and at most one dot, and the digit may be on either side of the dot — so "3." and ".8" are both valid while "." is not. The scan handles this by consuming digits and dots together, counting each, and then checking the digit count once at the end.

The exponent, if present, has its own optional sign and requires at least one digit — it may not contain a dot. The final i == n test is what rejects trailing junk and makes the whole thing airtight.

Approach

  1. Consume an optional leading sign.
  2. Consume digits and dots, counting both; reject on a second dot.
  3. Reject if no digit was seen.
  4. If e or E follows, consume an optional sign and then digits, rejecting if there are none.
  5. Accept only if the whole string was consumed.

Dry Run

verified against a regex reference on all 54,240 strings of length up to 4
over the alphabet 0-9 + - . e E -- every verdict agrees

  "0"         true
  "2e10"      true
  "-90E3"     true
  "53.5e93"   true
  "+6e-1"     true
  "3."        true      a digit before the dot is enough
  "+.8"       true      a digit after the dot is enough

  "e"         false     no mantissa
  "."         false     a dot with no digit
  " 1"        false     leading space is not in the grammar
  "1e"        false     exponent with no digits
  "99e2.5"    false     the exponent may not contain a dot
  "--6"       false     only one sign
  "-+3"       false
  "95a54e53"  false     stray letter, caught by the final i == n test
  ".e1"       false     no mantissa digit

Complexity

  • Time — O(n): each character is examined once; the scan never backtracks.
  • Space — O(1): a position and three counters.
  • A regular expression expresses the same grammar in one line and is the right answer in production. The hand scan is what the problem is testing, and it is also what you would write if the grammar needed extending.

Common Pitfalls

  • Accepting "." on its own. The dot is optional punctuation; the digit is mandatory.
  • Rejecting "3." or ".8". Both are valid — the digit may sit on either side.
  • Allowing a dot inside the exponent. "99e2.5" is invalid, which a shared digit-and-dot loop would wrongly accept if reused for the exponent.
  • Allowing more than one sign, or a sign anywhere other than at the very start or immediately after e.
  • Forgetting the final i == n check, which is the only thing rejecting trailing characters like the "a" in "95a54e53".
  • Trimming whitespace. This statement's alphabet contains no space, so a leading or trailing space is simply invalid — trimming would silently accept it.
  • Trying to enumerate states by hand with nested conditionals. It is doable and it is where the off-by-one cases hide; the linear scan with explicit counters is easier to argue about.

Full Solution — all languages

class Solution:
    def isNumber(self, s):
        i = 0
        n = len(s)
        if n == 0:
            return False
        if s[i] == '+' or s[i] == '-':
            i += 1
        digits = 0
        dots = 0
        while i < n and (s[i].isdigit() or s[i] == '.'):
            if s[i] == '.':
                dots += 1
                if dots > 1:
                    return False
            else:
                digits += 1
            i += 1
        if digits == 0:
            return False
        if i < n and (s[i] == 'e' or s[i] == 'E'):
            i += 1
            if i < n and (s[i] == '+' or s[i] == '-'):
                i += 1
            ed = 0
            while i < n and s[i].isdigit():
                ed += 1
                i += 1
            if ed == 0:
                return False
        return i == n
Asked at LinkedIn Nutanix
SensAI
Beta
Tap the mic to stop voice mode