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.
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").
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.
Let's validate the string "-123.45e+7".
-: Sign is allowed at the very beginning.123: Digits are allowed. digitSeen = true..: Dot is allowed because dotSeen and eSeen are false. dotSeen = true.45: Digits are allowed.e: Allowed because eSeen is false and digitSeen is true. eSeen = true, digitSeen = false (reset to ensure digits follow 'e').+: Sign allowed immediately after 'e'.7: Digits are allowed. digitSeen = true.digitSeen is true, so the number is valid.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.
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.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| String Compression III | Medium | Solve | |
| Minimum Number of Changes to Make Binary String Beautiful | Medium | Solve | |
| Count and Say | Medium | Solve | |
| Validate IP Address | Medium | Solve | |
| String to Integer (atoi) | Medium | Solve |