Home Leetcode

Valid Parentheses

Given a string s containing just the characters ’(’, ’)’, ’{’, ’}’, ’[’ and ’]’, determine if the input string is valid.

An input string is valid if:

  1. Open brackets must be closed by the same type of brackets.
  2. Open brackets must be closed in the correct order.
  3. Every close bracket has a corresponding open bracket of the same type.

Constraints:

The approach is clear straightforward: go through the string from left to right, making sure that all of the conditions are satisfied as we do so. The tricky part is how we make sure they are satisfied.

Notice that all of the conditions have to be satisfied as pairs.

This behaviour is last in, first out: the last open bracket considered is the first to be discarded. A stack is the perfect tool for the job.

def isValid(s: str) -> bool:
    stack = []

    for char in s:
        if char is an open bracket:
            add char to the stack
        if char is a closed bracket:
            if stack is empty: return False 

            pop the last open bracket off the stack
            if the last open bracket is not the same type:
                return False

    return whether stack is empty or not
    ...

There are two caveats that should be noted.

def isValid(self, s: str) -> bool:
    stack = []
    reverses = {
        "(": ")",
        "[": "]",
        "{": "}"
    }

    for char in s:
        if char in "([{":
            stack.append(reverses[char])
        elif char in ")]}":
            if len(stack) < 1:
                return False
            last = stack.pop()
            if last != char:
                return False

    return len(stack) == 0

Time Complexity

This algorithm has one loop of nn iterations, with each iteration taking constant time. Outside the loop, it only has constant time operations. Therefore, it is in O(n)\mathcal{O}(n) time.

Space Complexity

In the worst case, the stack has n2\frac{n}{2} elements inside. Other variables have constant space. Therefore, the algorithm uses O(n)\mathcal{O}(n) space.