Strict Numeric String Recognizer
StringsAuto-graded · 31 test casesLast updated
Tests whether candidates can implement a precise single-pass parser that accepts only well-formed integers, decimals, and scientific notation strings.
Problem Statement
Given a string s made up of ASCII characters, write a function that decides whether s encodes a valid number under the following strict rules.
Allowed Structure
A valid number is a base optionally followed by an exponent. Nothing else is permitted — no surrounding spaces, no extra characters.
Base — exactly one of:
-
A whole number: an optional
+or-sign, then one or more decimal digits (0–9). -
A decimal number: an optional
+or-sign, then one of:- one or more digits, a dot
., then one or more digits ("0.45") - one or more digits followed by a dot with nothing after it (
"2.") - a dot followed by one or more digits with nothing before it (
".8")
A lone dot, or a signed lone dot such as
"+.", is not a valid base — at least one digit must appear on some side of the dot. - one or more digits, a dot
Exponent (optional) — the letter e or E, then a valid whole number (optional sign, one or more digits). The exponent portion may not itself contain a dot or a nested exponent.
What is not allowed
- Whitespace anywhere in the string (leading, trailing, or embedded).
- A second dot, a dot inside the exponent, or two exponent markers.
- A sign that appears anywhere other than immediately after the start of the string or immediately after
e/E. - Alternative number notations: hexadecimal (
0x…), binary (0b…), octal, underscore separators, commas,inf,nan, etc.
Return True if s is a valid number under these rules, and False otherwise.
Constraints
1 <= len(s) <= 100sconsists of ASCII letters, decimal digits (0–9),'+','-','.', and whitespace characters.
Examples
Example 1
Input: is_valid_number('-0.1e+5')
Output: True
Example 2
Input: is_valid_number('1e2.5')
Output: False
Example 3
Input: is_valid_number(' .1 ')
Output: False
Example 4
Input: is_valid_number('2.')
Output: True
Hints
Hint 1
Walk the string left-to-right with a single index. Consume each grammar piece in order — base sign, integer digits, optional dot and fractional digits, optional exponent — and check at the end that the index reached exactly len(s).
Hint 2
A correct base needs at least one digit total, counting both the digits before the dot and the digits after it. Use two separate counters so you can enforce this rule regardless of whether a dot appeared.
Hint 3
For the exponent branch: only enter it when you actually see an 'e' or 'E', advance past it, allow one optional sign, then require at least one digit. If you enter the branch but find zero digits, the whole string is invalid. Any character the grammar never consumed — a space, a second dot, a letter like 'x' — will leave the index short of the end and fail the final check.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core idea: consume, then check for end-of-input
The grammar has a fixed, linear shape:
[sign] digits* [ '.' digits* ] [ (e|E) [sign] digits+ ]
\_______ base: ≥ 1 digit _______/
Rather than cataloguing every possible bad input, walk the string once with an index i, consuming each grammar piece in order. After processing every piece the grammar allows, check that i == len(s). If any character was never consumed — a space, a second dot, a stray letter, a sign in the wrong place — the index will fall short of the end and the string is rejected automatically.
Step by step
- Base sign — if
s[i]is+or-, advanceiby one. - Integer digits — count how many
0–9characters appear (digits_before). - Dot and fractional digits — if
s[i]is., advance past it, then count the digits that follow (digits_after). - Base validity check — if both
digits_beforeanddigits_afterare zero, the base contains no digits at all, so returnFalse. This single check rejects".","+.","e5", and the empty string. - Exponent — if
s[i]iseorE, advance past it, consume an optional sign, then count exponent digits. If the count is zero, returnFalse. This rejects"1e","1E-", and"e". - Final gate — return
i == n. Anything the grammar did not consume makes thisFalse.
Why the tricky cases fall out naturally
| Input | What happens |
|---|---|
".", "+." | digits_before == digits_after == 0 → rejected at step 4 |
"1.2.3" | Second dot is never consumed; i != n |
"1e2.5" | Dot inside exponent loop is never consumed; i != n |
"++1" | Second + is not a digit, so digits_before == 0, dot check fails, and base check rejects |
"1+" | + after digits is never consumed; i != n |
" .1 " | Leading space is never consumed; i != n |
"0x1F" | x stops the digit loop; i != n |
"2." | digits_before=1, digits_after=0 — valid base |
".8" | digits_before=0, digits_after=1 — valid base |
Note: digits are tested with "0" <= s[i] <= "9" rather than s[i].isdigit(). Python's isdigit() accepts Unicode digit characters such as ² and ٣, which this problem explicitly does not allow.
Complexity
- Time: O(n) — each character is visited at most once.
- Space: O(1) — only a handful of integer variables are used.
Full solution
def is_valid_number(s: str) -> bool:
if not s:
return False
i = 0
n = len(s)
# Advance past an optional +/- sign at position `pos`.
def consume_sign(pos: int) -> int:
if pos < n and s[pos] in "+-":
return pos + 1
return pos
# Consume an optional leading sign for the base.
i = consume_sign(i)
# Count digits before the decimal point.
digits_before = 0
while i < n and "0" <= s[i] <= "9":
digits_before += 1
i += 1
# Consume an optional dot, then count fractional digits.
digits_after = 0
if i < n and s[i] == ".":
i += 1
while i < n and "0" <= s[i] <= "9":
digits_after += 1
i += 1
# The base must have at least one digit on either side of the dot.
if digits_before == 0 and digits_after == 0:
return False
# Consume an optional exponent: e/E, optional sign, one or more digits.
if i < n and s[i] in "eE":
i += 1
i = consume_sign(i)
exponent_digits = 0
while i < n and "0" <= s[i] <= "9":
exponent_digits += 1
i += 1
if exponent_digits == 0:
return False
# Every character must have been consumed for the string to be valid.
return i == n