Magicsheet logo

Valid Number

Hard
20.3%
Updated 6/1/2025

Valid Number

What is this problem about?

The "Valid Number" interview question is a notoriously challenging string parsing problem. It requires you to determine if a given string represents a valid decimal number according to a strict set of rules. This includes handling signs (+ or -), decimal points (.), exponents (e or E), and digits. The complexity lies in the specific order and combination in which these characters can appear.

Why is this asked in interviews?

Tech giants like Apple, Amazon, and Google use the "Valid Number" coding problem to test a candidate's attention to detail and ability to handle complex edge cases. It’s a test of how you organize logic—whether you use a state machine, regular expressions, or a series of boolean flags to track what has been seen (e.g., "has seen digit," "has seen exponent").

Algorithmic pattern used

The "String interview pattern" for this problem often involves a Finite State Machine (FSM) or a flag-based approach. Using boolean variables like digitSeen, dotSeen, and eSeen allows you to validate each character based on what preceded it. For example, a dot cannot follow an exponent, and an exponent must be followed by at least one digit.

Example explanation

Let's validate the string "-123.45e+7".

  1. -: Sign is allowed at the very beginning.
  2. 123: Digits are allowed. digitSeen = true.
  3. .: Dot is allowed because dotSeen and eSeen are false. dotSeen = true.
  4. 45: Digits are allowed.
  5. e: Allowed because eSeen is false and digitSeen is true. eSeen = true, digitSeen = false (reset to ensure digits follow 'e').
  6. +: Sign allowed immediately after 'e'.
  7. 7: Digits are allowed. digitSeen = true.
  8. End of string. digitSeen is true, so the number is valid.

Common mistakes candidates make

The most common mistake is overlooking the requirement that an exponent must be followed by an integer. Another is allowing multiple decimal points or multiple exponents. Candidates also frequently forget that a standalone dot . or a sign followed by nothing else is not a valid number.

Interview preparation tip

When tackling the "Valid Number" coding problem, try to categorize the characters into groups (digits, signs, dots, exponents). Clearly define the rules for each group. Using a Finite State Machine is often the cleanest way to represent the logic and impress the interviewer with your architectural thinking.

Similar Questions