LeetCode Problem Workspace
Valid Number
Determine if a given string represents a valid number using precise string parsing and character validation rules.
1
Topics
6
Code langs
3
Related
Practice Focus
Hard · String-driven solution strategy
Answer-first summary
Determine if a given string represents a valid number using precise string parsing and character validation rules.
Ace coding interviews with Interview AiBoxInterview AiBox guidance for String-driven solution strategy
This problem requires analyzing each character of the input string to ensure it fits the valid number pattern. The solution focuses on handling optional signs, decimal points, and exponential notation while rejecting invalid sequences. Using a string-driven approach prevents common parsing mistakes and ensures accurate validation across all edge cases.
Problem Statement
Given a string s, determine whether it represents a valid number according to standard numerical formats. Valid numbers may include optional signs, decimal points, and exponential notation but must follow precise ordering rules.
For example, strings such as "2", "0089", "-0.1", "+3.14", "4.", "-.9", "2e10", "-90E3", "3e+7", "+6e-1", "53.5e93", and "-123.456e789" are valid, while "abc", "1a", "1e", "e3", "99e2.5", "--6", "-+3", and "95a54e53" are invalid.
Examples
Example 1
Input: s = "0"
Output: true
Example details omitted.
Example 2
Input: s = "e"
Output: false
Example details omitted.
Example 3
Input: s = "."
Output: false
Example details omitted.
Constraints
- 1 <= s.length <= 20
- s consists of only English letters (both uppercase and lowercase), digits (0-9), plus '+', minus '-', or dot '.'.
Solution Approach
Character-by-Character Validation
Scan the string from start to finish, checking each character for digits, decimal points, optional signs, or 'e'/'E'. Track whether a decimal or exponent has appeared to prevent invalid sequences, rejecting any unexpected characters immediately.
Handle Edge Cases and Boundaries
Special cases include strings starting or ending with a dot, strings with multiple signs, and exponents without numeric bases or powers. Explicitly handle empty numeric parts and misplaced symbols to ensure all invalid forms are caught.
Boolean Flags and State Tracking
Use flags to track the presence of digits, decimal points, and exponent sections. After scanning, validate that the final state represents a legitimate number, ensuring no trailing invalid characters exist and all required components are correctly positioned.
Complexity Analysis
| Metric | Value |
|---|---|
| Time | Depends on the final approach |
| Space | Depends on the final approach |
Time complexity depends on scanning each character once, making it O(n) where n is the length of the string. Space complexity is O(1) since only a few flags are maintained, independent of input size.
What Interviewers Usually Probe
- Check for correct handling of leading and trailing spaces, plus/minus signs, and dots.
- Expect edge cases where 'e' is present without proper numeric bases or exponents.
- Watch for multiple dots or misplaced signs that violate the valid number format.
Common Pitfalls or Variants
Common pitfalls
- Assuming any digit sequence is valid without validating decimal and exponent placement.
- Failing to reject strings with multiple signs or multiple dots.
- Overlooking cases where the exponent part is missing digits or improperly formatted.
Follow-up variants
- Validate numbers allowing only integers, disallowing decimal points and exponents.
- Check for scientific notation exclusively with 'E' or 'e' but reject plain decimals.
- Allow whitespace trimming at the beginning and end while maintaining numeric validation rules.
FAQ
What is the best way to approach Valid Number with a string-driven strategy?
Focus on scanning each character sequentially while tracking digits, decimal points, signs, and exponents, validating the state at each step.
Does a string with multiple dots or signs ever qualify as a valid number?
No, multiple dots or conflicting signs violate the numeric format and must be rejected.
How should exponent notation be handled?
Ensure the exponent 'e' or 'E' is preceded and followed by valid digits, optionally with a sign, and appears only once.
Are strings like '.' or 'e' considered valid?
No, a standalone dot or exponent without digits is invalid according to the number validation rules.
What is the time complexity of checking if a string is a valid number?
The time complexity is O(n), where n is the length of the string, since each character is examined exactly once.
Solution
Solution 1: Case Discussion
First, we check if the string starts with a positive or negative sign. If it does, we move the pointer $i$ one step forward. If the pointer $i$ has reached the end of the string at this point, it means the string only contains a positive or negative sign, so we return `false`.
class Solution:
def isNumber(self, s: str) -> bool:
n = len(s)
i = 0
if s[i] in '+-':
i += 1
if i == n:
return False
if s[i] == '.' and (i + 1 == n or s[i + 1] in 'eE'):
return False
dot = e = 0
j = i
while j < n:
if s[j] == '.':
if e or dot:
return False
dot += 1
elif s[j] in 'eE':
if e or j == i or j == n - 1:
return False
e += 1
if s[j + 1] in '+-':
j += 1
if j == n - 1:
return False
elif not s[j].isnumeric():
return False
j += 1
return TrueContinue Practicing
Continue Topic
string
Practice more edge cases under the same topic.
arrow_forwardauto_awesomeContinue Pattern
String-driven solution strategy
Expand the same solving frame across more problems.
arrow_forwardsignal_cellular_altSame Difficulty Track
Hard
Stay on this level to stabilize interview delivery.
arrow_forward