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
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
โ Linear Growth
Space Complexity
O(1)
Only using a few boolean flags and counters
โ Linear Space
Constraints
- 1 โค s.length โค 20
- s consists of only English letters (both uppercase and lowercase), digits (0-9), plus '+', minus '-', or dot '.'.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code