Skip to content
Problem 65 · LeetCode 65(opens in a new tab)

Valid Number

HardStrings

You are given a string s. Return true if it spells a number in the format below, and false if it does not.

A number is a base with an optional exponent after it. The base has an optional + or - sign, then one of: digits (17), digits and a dot (17.), digits, a dot and digits (1.7), or a dot and digits (.7). The exponent is e or E, then an optional sign, then at least one digit. Leading zeros are fine.

So "-0.6", "12e3" and "+.5E-2" are numbers, while "e5", "2e", "1e2.5" and "4-" are not.

Example 1

Input:  s = "-4.5e+3"
Output: true
Why:    a signed decimal, then e, then a signed integer
2 more examples and the constraints

Example 2

Input:  s = "7e"
Output: false
Why:    the exponent has no digits

Example 3

Input:  s = ".e1"
Output: false
Why:    the base is a dot with no digits on either side

Constraints

  • 1 ≤ length of s ≤ 20
  • s holds only English letters, digits, +, - and .

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Split by the rulesO(n)
  2. One pass with flagsO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for a 20-character stringVerdict
Split by the rulesO(n)
Passes; copies the parts
One pass with flagsO(n)
Best; one pass, no copies

n = length of s. Both are linear; the bars compare the constant factors.

Edge cases to test

  • A lone dot. "." has no digits on either side, so it is false.
  • e with nothing after it. "7e" and "3e+" fail: the exponent needs at least one digit.
  • e with nothing before it. "e5" and ".e1" fail: the base needs a digit.
  • Sign in the wrong place. "6+1" and "+-8" fail: a sign may only start the base or the exponent.
  • Dot after e. "4e1.5" fails: the exponent is a whole number.

Common mistakes

  • Forgetting to reset the digit flag at e, so "7e" is accepted.
  • Accepting a sign anywhere, so "6+1" passes.
  • Calling a language number parser, which also accepts things like "Infinity", " 5" or "0x1F".

How to talk through it

  1. 1Clarify. Are spaces allowed? Is "5." valid? Is ".5"? Can the exponent have a sign?
  2. 2Write the grammar. Sign, digits with at most one dot, then optionally e, sign and digits. Say it before coding.
  3. 3Give the split version. Split at e and at the dot and check each piece. It is linear but makes copies.
  4. 4Code one pass. Three flags; say the rule for each kind of character as you write its branch.
  5. 5Test out loud. Run ".", "7e", ".e1", "6+1" and "-4.5e+3" before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?