Valid Number (LeetCode 65): Solution and Explanation
Decide whether a string is a number of the form [sign] digits [. digits] [e [sign] digits], where the mantissa needs at least one digit on some side of the dot and the exponent needs its own digits. "0" is valid, "e" and "." are not.
Intuition
The grammar looks long, but every character type has exactly one rule about where it may stand. A digit can go anywhere. A sign can only open the number or open the exponent. A dot can appear once, and only before the exponent. An e can appear once, and only after some digits.
So you never need to backtrack. Read left to right and remember three facts: whether the current part has a digit yet, whether a dot has appeared, and whether an exponent has started.
When e arrives, the mantissa is finished and the exponent is a fresh integer, so reset the digit flag. At the end the string is valid exactly when the last part has at least one digit.
Approach: Single scan with three flags
- Set
seenDigit,seenDotandseenExpto false. - Digit: set
seenDigit. - Sign: valid only at index 0 or right after
e/E; otherwise return false. eorE: return false if an exponent was already seen or no digit came before it. Otherwise setseenExpand resetseenDigit.- Dot: return false if a dot or an exponent was already seen. Otherwise set
seenDot. - Any other character: return false.
- After the loop, return
seenDigit.
Step-by-step example
s = "0"
- All three flags start false.
- Read
0. It is a digit, so it fills the integer part andseenDigitbecomes true. - The string ends. The last part (the integer) has a digit, so the answer is
true. - Compare
"e": the first character isebutseenDigitis false, so it fails at once. And".": the dot is accepted, but the scan ends withseenDigitfalse, so the answer isfalse.
Code: Python, Java, C++
1class Solution:
2 def isNumber(self, s: str) -> bool:
3 seen_digit = seen_dot = seen_exp = False
4 for i, ch in enumerate(s):
5 if '0' <= ch <= '9':
6 seen_digit = True
7 elif ch in '+-':
8 if i > 0 and s[i - 1] not in 'eE':
9 return False
10 elif ch in 'eE':
11 if seen_exp or not seen_digit:
12 return False
13 seen_exp = True
14 seen_digit = False
15 elif ch == '.':
16 if seen_dot or seen_exp:
17 return False
18 seen_dot = True
19 else:
20 return False
21 return seen_digit1class Solution {
2 public boolean isNumber(String s) {
3 boolean seenDigit = false, seenDot = false, seenExp = false;
4 for (int i = 0; i < s.length(); i++) {
5 char ch = s.charAt(i);
6 if (ch >= '0' && ch <= '9') {
7 seenDigit = true;
8 } else if (ch == '+' || ch == '-') {
9 if (i > 0 && s.charAt(i - 1) != 'e' && s.charAt(i - 1) != 'E') {
10 return false;
11 }
12 } else if (ch == 'e' || ch == 'E') {
13 if (seenExp || !seenDigit) {
14 return false;
15 }
16 seenExp = true;
17 seenDigit = false;
18 } else if (ch == '.') {
19 if (seenDot || seenExp) {
20 return false;
21 }
22 seenDot = true;
23 } else {
24 return false;
25 }
26 }
27 return seenDigit;
28 }
29}1class Solution {
2public:
3 bool isNumber(string s) {
4 bool seenDigit = false, seenDot = false, seenExp = false;
5 for (int i = 0; i < (int)s.size(); i++) {
6 char ch = s[i];
7 if (ch >= '0' && ch <= '9') {
8 seenDigit = true;
9 } else if (ch == '+' || ch == '-') {
10 if (i > 0 && s[i - 1] != 'e' && s[i - 1] != 'E') {
11 return false;
12 }
13 } else if (ch == 'e' || ch == 'E') {
14 if (seenExp || !seenDigit) {
15 return false;
16 }
17 seenExp = true;
18 seenDigit = false;
19 } else if (ch == '.') {
20 if (seenDot || seenExp) {
21 return false;
22 }
23 seenDot = true;
24 } else {
25 return false;
26 }
27 }
28 return seenDigit;
29 }
30};Time and space complexity
O(n)
Each character is examined once with constant work.
O(1)
Only three boolean flags and a loop index.
Other approaches
Deterministic finite automaton (time O(n), space O(1))
Model the grammar as about nine states (start, sign, integer, dot after digits, dot first, fraction, exponent, exponent sign, exponent digits) with a transition table keyed by character class. Accept if the final state is one of the accepting ones. Same complexity, more code, but very systematic.
Regular expression (time O(n), space O(1))
Match ^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$. Short and correct, though interviewers usually want the hand-written scan.
Language number parser (time O(n), space O(1))
Calling float() or Double.parseDouble is tempting but wrong: they accept strings such as inf, nan, 1_000 or trailing f/d suffixes that this problem rejects.
Common mistakes
- Forgetting to reset the digit flag at
e. Without it,"1e"would be accepted because a digit was seen earlier. - Allowing a sign anywhere.
"6+1"and"-+3"are invalid: a sign must be first or come right aftere. - Rejecting
"4."or".5". A dot is fine with digits on only one side; only a lone"."(no digits at all) is invalid. - Allowing a dot inside the exponent, as in
"99e2.5". The exponent must be an integer.
Frequently asked questions
Why is "4." valid but "." not?
A decimal needs at least one digit, on either side of the dot. "4." has a digit before the dot. "." has none, so the final seenDigit check fails.
Why reset seenDigit when the exponent starts?
The exponent is a separate integer that needs its own digits. Resetting the flag makes the final check ask whether the exponent has digits, which rejects "1e" and "1e+".
Is the finite automaton solution better?
It is equivalent. The three flags are a compressed form of the automaton's state. The automaton is easier to extend if the grammar grows, while the flag version is shorter to write in an interview.