Skip to main content

Valid Number - Solution & Explanation

HardString24 min readAsked at: Amazon, Microsoft, Meta +4
Practice this problem

Problem Statement

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".

Formally, a valid number is defined using one of the following definitions:

  1. An integer number followed by an optional exponent.
  2. A decimal number followed by an optional exponent.

An integer number is defined with an optional sign '-' or '+' followed by digits.

A decimal number is defined with an optional sign '-' or '+' followed by one of the following definitions:

  1. Digits followed by a dot '.'.
  2. Digits followed by a dot '.' followed by digits.
  3. A dot '.' followed by digits.

An exponent is defined with an exponent notation 'e' or 'E' followed by an integer number.

The digits are defined as one or more digits.

 

Example 1:

Input: s = "0"

Output: true

Example 2:

Input: s = "e"

Output: false

Example 3:

Input: s = "."

Output: false

 

Constraints:

  • 1 <= s.length <= 20
  • s consists of only English letters (both uppercase and lowercase), digits (0-9), plus '+', minus '-', or dot '.'.

Approach Overview

Problem Overview: Given a string, determine whether it represents a valid numeric value. The string may contain digits, optional sign characters (+ or -), decimal points, and scientific notation using e or E. The challenge is validating the structure of the number while handling edge cases like multiple signs, misplaced decimals, or incomplete exponent parts.

Approach 1: Using Regular Expressions (O(n) time, O(1) space)

This approach relies on a carefully constructed regular expression that describes all valid numeric formats. The pattern checks optional leading signs, digits before or after a decimal point, and an optional exponent part like e+10. Once the pattern is defined, you simply run a regex match against the input string. Regex engines scan the string in linear time, so the complexity is O(n), and the memory overhead is constant aside from the compiled pattern. This approach is concise and easy to implement, especially in languages with strong regex support such as Python, Java, and JavaScript. The tradeoff is readability—debugging a complex regex can be difficult during interviews.

Approach 2: Iterative Parsing Approach (O(n) time, O(1) space)

This method scans the string once while tracking key conditions using boolean flags. As you iterate through characters, maintain flags such as seenDigit, seenDot, and seenExponent. Digits are always allowed, but a decimal point can appear only once and only before an exponent. The exponent character (e or E) must appear after at least one digit and resets the requirement that digits must follow. Sign characters are allowed only at the start of the string or immediately after an exponent. By validating each character under these rules, you effectively implement a lightweight parser. This approach is deterministic, interview-friendly, and commonly expected when solving string parsing problems.

Edge cases handled by this scan include inputs like ".1", "3.", "-90E3", and invalid cases such as "1e", "e3", or multiple decimal points. The algorithm only performs a single pass through the string, making it optimal for large inputs.

Recommended for interviews: The iterative parsing approach is typically preferred. It demonstrates your ability to reason about state transitions while processing a string. Regex works well in production code and quick scripts, but interviewers often want to see explicit logic instead of relying on regular expressions. Mentioning both approaches shows breadth: regex for brevity and manual parsing for algorithmic clarity.

Approach 1: Using Regular Expressions

A regular expression can be used to validate if a string is a valid number by matching patterns that define valid numbers. This pattern matches integers with optional signs, decimals, and scientific notation.

C language does not feature built-in regular expression checks. Therefore, this solution leverages the usage of the POSIX regex library to define patterns and match the string against it.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(n) due to scanning each character in the string.
Space Complexity: O(1) since we're using a fixed-size pattern.

Try this approach in the editor →

Approach 2: Iterative Parsing Approach

This approach involves parsing the string based on its characters and their positions. By iterating through the string, the method confirms whether it forms a valid number pattern based on segment rules.

This solution iteratively traverses the characters, checking the rules of valid numbers such as digits, signs, dots, and exponents. It carefully handles different cases to validate the string.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(n) where n is the length of the string.
Space Complexity: O(1) using variables to track state.

Try this approach in the editor →

Approach 3: Case Discussion

First, we check if the string starts with a positive or negative sign. If it does, we move the pointer i one step forward. If the pointer i has reached the end of the string at this point, it means the string only contains a positive or negative sign, so we return false.

If the character pointed to by the current pointer i is a decimal point, and there is no number after the decimal point, or if there is an e or E after the decimal point, we return false.

Next, we use two variables dot and e to record the number of decimal points and e or E respectively.

We use pointer j to point to the current character:

  • If the current character is a decimal point, and a decimal point or e or E has appeared before, return false. Otherwise, we increment dot by one;
  • If the current character is e or E, and e or E has appeared before, or if the current character is at the beginning or end of the string, return false. Otherwise, we increment e by one; then check if the next character is a positive or negative sign, if it is, move the pointer j one step forward. If the pointer j has reached the end of the string at this point, return false;
  • If the current character is not a number, return false.

After traversing the string, return true.

The time complexity is O(n), and the space complexity is O(1). Here, n is the length of the string.

Code

Python

Java

C++

Go

Rust

C#

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
Using Regular Expressions

Time Complexity: O(n) due to scanning each character in the string.
Space Complexity: O(1) since we're using a fixed-size pattern.

Iterative Parsing Approach

Time Complexity: O(n) where n is the length of the string.
Space Complexity: O(1) using variables to track state.

Case Discussion—

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Regular Expression MatchingO(n)O(1)When the language provides strong regex support and you want a concise validation rule
Iterative Parsing with FlagsO(n)O(1)Interview scenarios or when explicit validation logic is required

Video Solution

Valid Number | Live Coding with Explanation | Leetcode - 65 • Algorithms Made Easy • 12,721 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is Valid Number easy or hard?
Valid Number is classified as a Hard problem because of the large number of edge cases. The logic itself is straightforward once broken into rules, but ensuring all valid formats and rejecting invalid ones requires careful state tracking.
How to solve Valid Number in O(n)?
Traverse the string once while maintaining boolean flags such as seenDigit, seenDot, and seenExponent. Allow digits anywhere, allow a decimal only once before an exponent, and ensure an exponent appears only after at least one digit. Sign characters are valid only at the start or immediately after an exponent. This single-pass validation guarantees O(n) time complexity.
Valid Number Python or Java solution?
Both Python and Java solutions typically implement a single-pass parser with boolean flags. Python solutions may also use the re module for regex matching, while Java commonly uses character iteration with conditions. In both languages the optimal complexity remains O(n) time and O(1) space.
What is the best approach for Valid Number?
The iterative parsing approach is generally the best solution. It scans the string once while tracking rules for digits, decimal points, signs, and exponents using simple flags. This method runs in O(n) time and O(1) space and clearly demonstrates understanding of string parsing logic, which interviewers typically expect.
What data structure is used in Valid Number?
The problem mainly uses string traversal with a few boolean state variables. No complex data structures are required. The algorithm relies on parsing rules that track whether digits, decimal points, or exponent markers have already appeared.
What is the time complexity of Valid Number?
Both common solutions run in O(n) time where n is the length of the string. Each character is processed once either by the regex engine or a manual parsing loop. Space complexity is O(1) because only a few flags or a compiled pattern are stored.
Is Valid Number asked at Google, Amazon, or Meta?
Valid Number is a classic string parsing problem that has appeared in interviews at companies like Google, Amazon, and Meta. It tests careful handling of edge cases and state-based validation rather than heavy data structures or algorithms.

Ready to solve this problem?

Practice Valid Number with our built-in code editor and test cases.

Practice on FleetCode