Valid Parentheses

Check that every bracket in a string is closed by the right type of bracket, in the right order.

Given a string s made only of the characters '(', ')', '{', '}', '[' and ']', return true if its brackets are valid and false otherwise. The brackets are valid when every opening bracket is closed by a bracket of the same type, brackets close in the right order, and every closing bracket closes an opening one.

Example 1
Input: s = "()"
Output: true
Example 2
Input: s = "()[]{}"
Output: true
Example 3
Input: s = "(]"
Output: false
Explanation: '(' is closed by the wrong type of bracket.
Example 4
Input: s = "([)]"
Output: false
Explanation: there is one of each bracket, but '(' closes before '[', which was opened after it.
Solution

The Idea

You have probably written brackets inside brackets, in arithmetic such as 2 Ɨ (3 + [4 āˆ’ 1]) or in Java, where a method's braces sit inside a class's braces. Each pair wraps a part of the text, and an inner pair must end before the outer one does, like a small box inside a bigger box.

Example 4, "([)]", breaks that rule. The square bracket opens inside the round one, but the round one closes first, so the two boxes overlap. Swap the last two characters and you get "([])", which is valid. Counting cannot tell these two strings apart, because both have one '(', one ')', one '[' and one ']'. So which opening bracket must a closing bracket match?

It must match the most recent opening bracket that is still open. Read the string from left to right and keep the open brackets in a pile, putting each new one on top. A closing bracket must match the bracket on top, which is then closed and comes off the pile. Look at the picture below.

Reading "([])" and "([)]" from left to right while keeping a pile of open brackets, newest on top. In "([])" each closing bracket closes the bracket on top and nothing is left open, so it is valid. In "([)]" the ) arrives while [ is on top, so it is invalid.

In the top row, "([])" puts ( and then [ on the pile. The ] closes the [ on top, the ) closes the (, and the row ends with "nothing left open: valid". In the bottom row, "([)]" builds the same pile, but then ) arrives while [ is on top. The orange box marks that moment: the [ would have to close first, so the string is invalid, and the last character does not even need reading.

A pile where you only add to the top and only take from the top is called a stack. The last bracket put on comes off first, which is exactly the order in which brackets must close.

Solution Approach

Turning the pile into code means settling three things: which Java class holds the stack, what goes on it, and the ways a string can fail. First, though, a slower method without a stack shows what the stack saves.

Removing pairs one round at a time

Is a stack really needed? A valid string that is not empty always has a matched pair side by side somewhere, such as "()" or "[]". Delete every such pair, and what is left must still be valid. Repeat until nothing changes, and the string was valid if nothing is left.

This works, but each round scans the whole string, and a deeply nested string loses only one pair per round. "((((()))))" needs five rounds to become empty. In general that is up to n/2 rounds of up to n steps each, about n² steps for a string of n characters. The stack reads each character once.

Holding the stack in Java

Which class should hold the stack? Java has an old class named Stack, but its own documentation recommends the Deque interface instead. A Deque (a double-ended queue, pronounced "deck") can add and remove items at both ends, and ArrayDeque is its implementation backed by an array. Its push puts an item on top, pop removes the top item and returns it, and isEmpty tells whether anything is left.

What goes on the stack

Should the stack hold the opening brackets themselves, as the picture does? It can, but then each closing bracket needs a lookup to find which opening bracket it belongs to. It is simpler to push the closing bracket that each opener is waiting for: ) for (, ] for [ and } for {. A closing bracket is then correct exactly when it equals the character on top.

Three ways to fail

When is the answer false? A closing bracket can arrive when the stack is empty, as in ")", where nothing is open. It can differ from the top, which covers both a wrong type, as in "(]", and a wrong order, as in "([)]". Or the string can end with brackets still on the stack, as in "(((", where something was opened and never closed. If none of these happens, the string is valid.

Java Solution

The method isValid works in these steps:

  1. First, create an empty stack named expected, an ArrayDeque of characters. It holds the closing brackets the string still owes.
  2. Loop over the characters of s, one character c at a time, and choose what to do with a switch on c.
  3. For an opening bracket, push its closing partner onto expected: ) for (, ] for [ and } for {.
  4. Any other character is a closing bracket and goes to the default branch. If expected is empty, or the bracket popped from its top differs from c, return false at once.
  5. After the loop, return expected.isEmpty(), which is true only if every opening bracket was closed.

The main method runs the four examples, the valid "([])" from the picture, the nested "{[()]}", the empty string, and two strings that fail in the other ways, "(((" and "())".

Java
import java.util.ArrayDeque;
import java.util.Deque;

public class ValidParentheses {

    public static boolean isValid(String s) {
        Deque<Character> expected = new ArrayDeque<>();   // closing brackets we still need
        for (char c : s.toCharArray()) {
            switch (c) {
                case '(' -> expected.push(')');
                case '[' -> expected.push(']');
                case '{' -> expected.push('}');
                default -> {                                // a closing bracket
                    if (expected.isEmpty() || expected.pop() != c) {
                        return false;                       // nothing open, or the wrong one
                    }
                }
            }
        }
        return expected.isEmpty();                          // every opening bracket was closed
    }

    public static void main(String[] args) {
        String[] tests = {"()", "()[]{}", "(]", "([)]", "([])", "{[()]}", "", "(((", "())"};
        for (String s : tests) {
            System.out.println("\"" + s + "\" -> " + isValid(s));
        }
    }
}

Running it prints:

Output
"()" -> true
"()[]{}" -> true
"(]" -> false
"([)]" -> false
"([])" -> true
"{[()]}" -> true
"" -> true
"(((" -> false
"())" -> false

Compare "([)]" -> false with "([])" -> true right below it: the same four brackets, and only the order of the last two differs, just as in the picture. "{[()]}" nests all three types and passes. The empty string prints true, because the loop never runs and expected is still empty.

The last two lines fail in the ways the examples do not show. "(((" never meets a wrong closing bracket, so only the final expected.isEmpty() catches it. A version that simply returns true after the loop prints true for "(((". In "())", the second ) finds expected empty, so the method returns false.

The original implementation, ValidParentheses.java, is on GitHub.

Complexity

The method reads the string once and keeps one stack.

  • Time: O(n), because each of the n characters is read once and costs either one push, or one pop and one comparison.
  • Space: O(n), because the stack holds one closing bracket for each opening bracket not yet closed, and a string such as "((((" keeps all of its n characters open at once.

With only one type of bracket, a count of the open brackets can replace the stack, as in Minimum Add to Make Parentheses Valid.