Python 0065.py
class Solution:
def isNumber(self, s: str) -> bool:
return re.search("^[-+]?([0-9]+\.?|[0-9]*\.[0-9]+)([eE][-+]?[0-9]+)?$", s)
Difficulty
and has an acceptance rate of about 23% (2+ million submissions).
Typical patterns to solve this problem:
- String
AI Disclaimer
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.
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 as123..[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, like12.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.14or-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+2or+.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.
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.
Code Quality
Complexity Analysis
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
Other Solutions
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++ |
Videos
Similar Problems
- problem 8: String to Integer (atoi)
Solved On The Same Day
- problem 144: Binary Tree Preorder Traversal
- problem 145: Binary Tree Postorder Traversal
- problem 222: Count Complete Tree Nodes
- problem 404: Sum of Left Leaves
- problem 501: Find Mode in Binary Search Tree
- problem 543: Diameter of Binary Tree
- problem 559: Maximum Depth of N-ary Tree
- problem 589: N-ary Tree Preorder Traversal
- problem 590: N-ary Tree Postorder Traversal
- problem 637: Average of Levels in Binary Tree
- problem 700: Search in a Binary Search Tree
- problem 703: Kth Largest Element in a Stream
- problem 79: Word Search
- problem 81: Search in Rotated Sorted Array II
- problem 97: Interleaving String
- problem 99: Recover Binary Search Tree
- problem 173: Binary Search Tree Iterator
- problem 199: Binary Tree Right Side View
- problem 230: Kth Smallest Element in a BST
- problem 235: Lowest Common Ancestor of a Binary Search Tree
- problem 341: Flatten Nested List Iterator
- problem 429: N-ary Tree Level Order Traversal
- problem 508: Most Frequent Subtree Sum
- problem 513: Find Bottom Left Tree Value
- problem 538: Convert BST to Greater Tree
- problem 85: Maximal Rectangle
- problem 87: Scramble String
- problem 126: Word Ladder II
- problem 127: Word Ladder
Fun Facts
This hard problem has the lowest acceptance rate of just 23%.
Extra
- 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