Problem StatementGiven an input string, determine if it makes a valid number or not. For simplicity, assume that white spaces are not present in the input.4.325 is a valid number.
1.1.1 is NOT a valid number.
222 is a valid number.
22. is NOT a valid number.
0.1 is a valid number.
22.22. is NOT a valid number.
1. is NOT a valid number.
Use state machine
Linear, O(n).
Constant, O(1).
We’ll use the state machine below to check if a number is valid or not. The initial state is ‘Start’. We’ll process each character to identify the next state. The input string is not a valid number if we reach an UNKNOWN state at any point or if it ends in a DECIMAL.
We are not looking at the sign (+ or -) at the start of a number in the state machine. If there is a sign at the start of the input string, we start processing the string for the state machine after that sign character.
Practice problems like this and many more by checking out our Grokking the Coding Interview: Patterns for Coding Questions course!