Problem 65

Abstract / Summary

Check if a string represents a valid number using allowed formats like integers decimals scientific notation.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0065.py

class Solution:
    def isNumber(self, s: str) -> bool:
        return re.search("^[-+]?([0-9]+\.?|[0-9]*\.[0-9]+)([eE][-+]?[0-9]+)?$", s)
3 lines | 142 bytes | submitted September 1, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 23% (2+ million submissions).

Typical patterns to solve this problem:
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a Solution class with a single method isNumber. The method receives a string s and determines whether the entire string conforms to the lexical definition of a numeric literal. The decision is made by applying a regular expression that captures the optional sign, the integral and fractional components, and an optional exponent part. The result of the regular expression search is returned directly, leveraging Python’s truth-value testing of match objects.

Core Logic

The central operation is a call to re.search with a pattern that is anchored at both the start (^) and the end ($) of the input. This anchoring guarantees that only strings that completely match the pattern are considered valid numbers.

re.search("^[-+]?([0-9]+\\.?|[0-9]*\\.[0-9]+)([eE][-+]?[0-9]+)?$", s)

Optional Sign

The sub-pattern [-+]? at the beginning allows for an optional leading plus or minus sign. By making the sign optional, the expression accepts both signed and unsigned numbers without requiring additional conditional logic.

Integral and Fractional Parts

The expression ([0-9]+\\.?|[0-9]*\\.[0-9]+) captures the main numeric portion. It consists of two alternatives:

  • [0-9]+\\.? matches one or more digits optionally followed by a decimal point. This branch accepts integers as well as numbers that end with a trailing dot, such as 123..
  • [0-9]*\\.[0-9]+ matches an optional sequence of digits, a mandatory decimal point, and at least one digit after the point. This branch covers numbers that start with a dot, like .456, and numbers with digits on both sides of the dot, like 12.34.

By combining these alternatives, the pattern handles all conventional placements of the decimal point while ensuring that at least one digit appears somewhere in the mantissa.

Exponent Component

The optional group ([eE][-+]?[0-9]+)? deals with scientific notation. It permits either a lower-case e or an upper-case E, followed by an optional sign and one or more digits. The entire group is optional, allowing plain decimal numbers to be accepted without an exponent.

Full-String Matching

The leading ^ and trailing $ anchors enforce that the regular expression must consume the entire input string. Consequently, any extraneous characters before or after the numeric literal cause the match to fail, eliminating the need for additional trimming or validation steps.

Edge Cases Addressed

The pattern inherently supports several edge cases:

  • Numbers with a leading sign, such as +3.14 or -0.001.
  • Integers without a decimal point, for example 42.
  • Numbers that end with a decimal point, like 7..
  • Numbers that begin with a decimal point, such as .9.
  • Scientific notation with optional sign in the exponent, for instance 6.022e23, 1e-9, or -2E+5.
  • Mixed forms that combine the above, e.g., -3.5e+2 or +.8E-1.

Because the regular expression requires at least one digit either before or after the decimal point, inputs consisting solely of a sign, a lone decimal point, or an isolated exponent (e.g., +, ., e10) are correctly rejected.

Performance Considerations

The implementation relies on Python’s built-in re module, which employs a compiled finite-state automaton for pattern matching. The use of anchored patterns (^ and $) limits the search space to a single pass over the input, avoiding backtracking beyond the bounds of the string. The pattern itself is concise, using character classes and quantifiers that the regex engine can evaluate efficiently. By avoiding explicit loops or multiple conditional checks in Python code, the solution delegates the heavy lifting to the highly optimized C implementation of the regex engine, resulting in fast execution for typical input sizes.

Code Structure

The method is defined as a single expression, returning the result of the regular expression search directly. This compact form eliminates intermediate variables and makes the control flow straightforward.

class Solution:
    def isNumber(self, s: str) -> bool:
        return re.search("^[-+]?([0-9]+\\.?|[0-9]*\\.[0-9]+)([eE][-+]?[0-9]+)?$", s)

The class encapsulation follows the common pattern used in coding challenge platforms, allowing the method to be invoked in a standardized testing harness. The type annotation s: str clarifies the expected input type, while the return type hint -> bool signals that callers should interpret the result in a boolean context, even though the underlying object is a match instance. This design leverages Python’s dynamic typing while providing useful documentation for developers.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a giant robot that loves collecting pieces of paper with scribbles on them. Some of these scribbles are numbers and some are just silly drawings. The robot has a special detective tool that looks at a piece of paper to decide if the scribble is a proper number.

The rule starts by looking for a tiny sign at the beginning, like a plus or a minus, to see if the number is going up or down. Next, the robot checks for digits, which are the numbers zero through nine, to see if there is enough information to count something. Sometimes a number has a special dot in the middle, or it might have a letter e inside, which is a fancy way to say that the number is really, really big or really, really tiny. The robot follows these strict rules to check every part of the scribble from the very start to the very end. If everything matches the pattern perfectly, the robot decides that the scribble is indeed a number.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 4 | μ = 5.00 | σ = 1.96

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Rust Java C# Go
LeetcodeHelp C++ Python Java
Progiez C++ Python Java
github aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++
charles-wangkai Java
chenyanzhe C++
everthis JS
gaosq0604 Python
Garvit244 Python
halfrost Go
haoel C++
JoshCrozier JS
keineahnung2345 C++
lennylxx C
linouk23 C++
lkwq007 Python
luangong C++
MacJim C++
qiyuangong Python
ruoru Rust
suxrobGM C#
varunu28 Java
vli02 C
wisdompeak C++
XiaotaoGuo C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, C#, Go, Java, Python, Rust
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++, C++
charles-wangkai Java
chenyanzhe C++
everthis JavaScript
gaosq0604 Python
Garvit244 Python
halfrost Go
haoel C++
JoshCrozier JavaScript
keineahnung2345 C++
lennylxx C
linouk23 C++
lkwq007 Python
luangong C++
MacJim C++
qiyuangong Python
ruoru Rust
suxrobGM C#
varunu28 Java
vli02 C
wisdompeak C++
XiaotaoGuo C++
44 links | 30 authors | 9 languages

Videos

13 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

30 solutions   September 1, 2023

Fun Facts

This hard problem has the lowest acceptance rate of just 23%.

1 fun fact

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality