HardNo. 0065

Valid Number — LeetCode 65 Python Solution

Pattern
Hash Map
Topics
String
Reading time
5 min

The problem

Given a string s, return whether s is a valid number. For example, all the following are valid numbers: "2", "0089", "-0.1", "+3.14", "4.", "-.9", "2e10", "-90E3", "3e+7", "+6e-1", "53.5e93", "-123.456e789", while the following are not valid numbers: "abc", "1a", "1e", "e3", "99e2.5", "--6", "-+3", "95a54e53".

Python solution

PythonSolution
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 True

Complexity

Time
O(n)
Space · auxiliary
O(1)

Pattern: Hash Map

Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 65. Valid Number is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.

The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0068Text JustificationHard
0058Length of Last WordEasy
0006Zigzag ConversionMedium
0008String to Integer (atoi)Medium
0038Count and SayMedium
0214Shortest PalindromeHard

Frequently asked questions

How hard is LeetCode 65. Valid Number?

LeetCode 65. Valid Number is rated Hard on LeetCode.

What is the time complexity of LeetCode 65. Valid Number?

The Python solution on this page runs in O(n).

What is the space complexity of LeetCode 65. Valid Number?

The Python solution on this page uses O(1) auxiliary space.

What topics does LeetCode 65. Valid Number cover?

LeetCode 65. Valid Number is tagged String on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.