Today's challenge look simple, but there are some cases that makes it a bit difficult.

The challenge was to check whether the given string is a valid number or not. I listed some of the examples from the challenge. If you need more description about the challenge, you can find more detail here.

Example 1:

Input: s = "0"
Output: true

Example 2:

Input: s = "e"
Output: false

Example 3:

Input: s = "."
Output: false

The solution

My first intuition was to type cast the number to float. If the number casts to float without any problem, then it is valid. If not, it is invalid. This intuition doesn't work for the cases like “inf”, “NaN”s.

Then I tried checking the string whether it contains all letters, “-inf” will disqualify this check as well.

The reason I don't want to use regular expression at first was to make my algorithm run faster but I ended up using it after all the failed trails. The regular expressions won't work alone either; “0e” kind of value gives unwanted result. So, I combined the regular expressions with my previous intuitions.

The result

Runtime: 34 ms, faster than 95.67% of Python3 online submissions for Valid Number.

Memory Usage: 13.9 MB, less than 75.31% of Python3 online submissions for Valid Number.