Valid Number - Problem

Determining if a string represents a valid number is a classic parsing challenge that tests your understanding of formal grammar rules and string processing.

Given a string s, return true if s is a valid number, otherwise return false.

A valid number can be:

  • Integer: Optional sign followed by digits (e.g., "2", "-42", "+0089")
  • Decimal: Optional sign + digits with decimal point (e.g., "-0.1", "4.", ".9")
  • Scientific notation: Integer or decimal followed by 'e'/'E' and integer exponent (e.g., "2e10", "3.14E-5")

Valid examples: "2", "0089", "-0.1", "+3.14", "4.", "-.9", "2e10", "-90E3", "3e+7"

Invalid examples: "abc", "1a", "1e", "e3", "99e2.5", "--6", "-+3"

Input & Output

example_1.py โ€” Valid Integer
$ Input: s = "42"
โ€บ Output: true
๐Ÿ’ก Note: Simple integer number with digits only is valid
example_2.py โ€” Valid Scientific Notation
$ Input: s = "-123.45e+6"
โ€บ Output: true
๐Ÿ’ก Note: Negative decimal number with positive exponent: -123.45 ร— 10^6
example_3.py โ€” Invalid Format
$ Input: s = "1e"
โ€บ Output: false
๐Ÿ’ก Note: Exponent notation requires digits after 'e', but none provided

Visualization

Tap to expand
Number Validation JourneyFollowing the path of "-123.45e+6"STARTSIGNEDDIGITDEC_DIGEXPEXP_SIGNEXP_DIG-123.45e+6โœ“ VALID๐ŸŸข Green = Valid ending states | ๐ŸŸ  Orange = Intermediate states
Understanding the Visualization
1
Start State
Begin parsing, expecting sign, digit, or decimal point
2
Process Sign
If sign found, transition to signed state, expecting digit or decimal
3
Handle Digits
Accumulate digits, can transition to decimal or exponent
4
Decimal Processing
Handle decimal point and fractional digits
5
Exponent Handling
Process 'e'/'E' followed by optional sign and required digits
6
Validate End State
Ensure we end in a valid final state
Key Takeaway
๐ŸŽฏ Key Insight: A finite state machine elegantly handles all number validation rules by defining clear states and valid transitions, ensuring we process the string systematically in just one pass.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n)

Multiple passes through string, but still linear

n
2n
โœ“ Linear Growth
Space Complexity
O(1)

Only using a few boolean flags and counters

n
2n
โœ“ Linear Space

Constraints

  • 1 โ‰ค s.length โ‰ค 20
  • s consists of only English letters (both uppercase and lowercase), digits (0-9), plus '+', minus '-', or dot '.'.
Asked in
Google 15 Amazon 12 Microsoft 8 Meta 6
24.5K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen