Valid Number

Hard Arrays & Hashing Simulation

Valid Number is a hard arrays & hashing problem solved with the simulation pattern. The best approach, optimal (one pass with three flags), runs in O(n) time and O(1) space. Below are 3 approaches in Java, Python, C++ and JavaScript, from brute force (split at the exponent, check each part) up.

Problem

Given a string s, return true if it is a valid number and false otherwise.

A valid number is a decimal or an integer, optionally followed by an exponent:

  • An integer is an optional sign ('+' or '-') followed by one or more digits.
  • A decimal is an optional sign followed by digits with one point '.' somewhere among them: digits then a point ("4."), digits, a point and more digits ("3.14"), or a point then digits (".5"). At least one digit is required.
  • An exponent is the letter 'e' or 'E' followed by an integer.

So "2", "0089", "-0.1", "+3.14", "4.", "-.9", "2e10", "-90E3", "3e+7" and "53.5e93" are valid, while "abc", "1a", "1e", "e3", "99e2.5", "--6", "-+3" and "95a54e53" are not.

Examples

Example 1

Input
s = "-12.5e+3"
Output
true
Why
A sign, the decimal 12.5, then an exponent made of e, a sign and the integer 3. Every part follows the rules.

Example 2

Input
s = "7e"
Output
false
Why
An exponent marker must be followed by an integer, and here nothing comes after the e.

Example 3

Input
s = "4."
Output
true
Why
A decimal may end with its point, as long as it has at least one digit somewhere.

Example 4

Input
s = "2.5e1.5"
Output
false
Why
The part after the exponent marker must be an integer, so it cannot contain a point.

Constraints

  • 1 <= s.length <= 20
  • s consists only of English letters (upper and lower case), digits 0-9, plus '+', minus '-' and dot '.'.

Solve it here

Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.

00:00
Testcase

Run checks the testcases above (4 examples, or your own). Submit also runs 14 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.

Animated walkthrough

A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

Solutions

Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.

ApproachTimeSpace
Brute force (split at the exponent, check each part)O(n)O(1)
Finite-state machineO(n)O(1)
Optimal (one pass with three flags)O(n)O(1)

1Brute force (split at the exponent, check each part)

TimeO(n)One scan to find the marker, then one scan of each part, so every character is read at most twice.
SpaceO(1)Only indexes and counters; the parts are checked in place without building substrings.

Turn the definition into code piece by piece. Find the exponent marker e or E; if there are two of them, the string is invalid. Without a marker the whole string must be a decimal or an integer. With one, the part before it must be a decimal or an integer and the part after it must be an integer. A decimal or integer is: an optional sign, then only digits and at most one point, with at least one digit. An integer is the same without any point. Each part is scanned on its own, so some characters are looked at twice.

  1. Scan s for e or E. Two markers: return false. Remember where the marker is.
  2. No marker: return whether all of s is a decimal (sign, digits, at most one point, at least one digit).
  3. One marker at index e: return whether s[0..e) is a decimal and s(e..n) is an integer (sign, then one or more digits, nothing else).
class Solution {
    public boolean isNumber(String s) {
        int e = -1;
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c == 'e' || c == 'E') {
                if (e != -1) return false;
                e = i;
            }
        }
        if (e == -1) return isDecimal(s, 0, s.length());
        return isDecimal(s, 0, e) && isInteger(s, e + 1, s.length());
    }

    private boolean isDecimal(String s, int from, int to) {
        if (from < to && (s.charAt(from) == '+' || s.charAt(from) == '-')) from++;
        int digits = 0, dots = 0;
        for (int i = from; i < to; i++) {
            char c = s.charAt(i);
            if (c >= '0' && c <= '9') digits++;
            else if (c == '.') dots++;
            else return false;
        }
        return digits > 0 && dots <= 1;
    }

    private boolean isInteger(String s, int from, int to) {
        if (from < to && (s.charAt(from) == '+' || s.charAt(from) == '-')) from++;
        if (from == to) return false;
        for (int i = from; i < to; i++) {
            char c = s.charAt(i);
            if (c < '0' || c > '9') return false;
        }
        return true;
    }
}

2Finite-state machine

TimeO(n)One table lookup per character.
SpaceO(1)The table has a fixed 9 by 4 size, whatever the input.

Read the string one character at a time and keep a single state that says what has been read so far: nothing, a sign, integer digits, a point after digits, a point with no digits yet, fraction digits, the exponent marker, the exponent's sign, or exponent digits. Every character falls into one of four classes (digit, sign, point, e/E) or is illegal. A table gives the next state for each state and class, with -1 meaning no legal move. The string is a number when the input ends in a state that has read a complete number: integer digits, a point after digits, fraction digits or exponent digits.

  1. Classify each character: digit 0, sign 1, point 2, e or E 3; anything else returns false.
  2. Start in state 0 and move with next[state][class]. If the move is -1, return false.
  3. After the last character, return whether the state is one of the accepting states 2, 3, 5 or 8.
class Solution {
    private static final int[][] NEXT = {
        { 2,  1,  4, -1},   // 0: start
        { 2, -1,  4, -1},   // 1: sign
        { 2, -1,  3,  6},   // 2: integer digits
        { 5, -1, -1,  6},   // 3: point after digits
        { 5, -1, -1, -1},   // 4: point, no digits yet
        { 5, -1, -1,  6},   // 5: fraction digits
        { 8,  7, -1, -1},   // 6: e or E
        { 8, -1, -1, -1},   // 7: exponent sign
        { 8, -1, -1, -1},   // 8: exponent digits
    };

    public boolean isNumber(String s) {
        int state = 0;
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            int kind;
            if (c >= '0' && c <= '9') kind = 0;
            else if (c == '+' || c == '-') kind = 1;
            else if (c == '.') kind = 2;
            else if (c == 'e' || c == 'E') kind = 3;
            else return false;
            state = NEXT[state][kind];
            if (state == -1) return false;
        }
        return state == 2 || state == 3 || state == 5 || state == 8;
    }
}

3Optimal (one pass with three flags)

TimeO(n)One pass with constant work per character.
SpaceO(1)Three booleans and the loop index.

The state machine can be squeezed into three booleans: seenDigit, seenDot and seenExp. A digit sets seenDigit. A sign is legal only as the first character or right after e or E. A point is legal only if there has been no point and no exponent yet. An e or E is legal only if there has been no exponent yet and some digit came before it; it then clears seenDigit, because the exponent needs digits of its own. Any other character is illegal. At the end the string is a number exactly when seenDigit is true, which means the last part, the mantissa or the exponent, has at least one digit.

  1. Set seenDigit, seenDot and seenExp to false.
  2. For each character c at index i: a digit sets seenDigit. A sign with i > 0 and s[i - 1] not e or E returns false.
  3. A point when seenDot or seenExp returns false; otherwise set seenDot.
  4. An e or E when seenExp or not seenDigit returns false; otherwise set seenExp and clear seenDigit. Any other character returns false.
  5. Return seenDigit.
class Solution {
    public boolean isNumber(String s) {
        boolean seenDigit = false, seenDot = false, seenExp = false;
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c >= '0' && c <= '9') {
                seenDigit = true;
            } else if (c == '+' || c == '-') {
                if (i > 0 && s.charAt(i - 1) != 'e' && s.charAt(i - 1) != 'E') return false;
            } else if (c == '.') {
                if (seenDot || seenExp) return false;
                seenDot = true;
            } else if (c == 'e' || c == 'E') {
                if (seenExp || !seenDigit) return false;
                seenExp = true;
                seenDigit = false;
            } else {
                return false;
            }
        }
        return seenDigit;
    }
}

Edge cases to test

  • A lone dot "." or a lone sign "+" has no digit at all, so it is not a number
  • A point at either end is fine when there are digits on the other side: "4." and ".5" are both valid
  • An exponent with nothing before it ("e9") or nothing after it ("9e", "9e+") is invalid
  • A point after the exponent ("1e2.5") or a second exponent ("1e2e3") is invalid
  • A sign is allowed only at the very start or right after e / E: "1+2" and "+-3" are invalid
  • Both e and E mark the exponent; every other letter makes the string invalid, including words like "inf"
  • Leading zeros are allowed: "0089" is a number

Hints

Hint 1

Write the grammar down first: number = decimal or integer, optionally followed by an exponent; exponent = e or E, then an integer.

Hint 2

There can be at most one e or E. Splitting the string at it gives a left part that must be a decimal or integer and a right part that must be an integer.

Hint 3

In one left-to-right pass you only need to remember three things: have I seen a digit, a point, an exponent? When you meet the e, reset the digit flag, because the exponent needs digits of its own.

Hint 4

A sign is legal only at index 0 or right after an e. At the end, the answer is whether the last group of digits was non-empty.

FAQ

What is the best time complexity for Valid Number?

Optimal (one pass with three flags) runs in O(n) time and O(1) extra space. One pass with constant work per character.

Which pattern does Valid Number use?

It is a arrays & hashing problem that uses the simulation pattern. Other problems with the same pattern: Text Justification, Integer to English Words, String to Integer (atoi).

Is there a brute force solution for Valid Number?

Yes. Brute force (split at the exponent, check each part) takes O(n) time and O(1) space. Turn the definition into code piece by piece.

Which edge cases should I test for Valid Number?

A lone dot "." or a lone sign "+" has no digit at all, so it is not a number; A point at either end is fine when there are digits on the other side: "4." and ".5" are both valid; An exponent with nothing before it ("e9") or nothing after it ("9e", "9e+") is invalid; A point after the exponent ("1e2.5") or a second exponent ("1e2e3") is invalid; A sign is allowed only at the very start or right after e / E: "1+2" and "+-3" are invalid; Both e and E mark the exponent; every other letter makes the string invalid, including words like "inf"; Leading zeros are allowed: "0089" is a number.