Algo-Sim › Stacks & Monotonic Stack

Valid Parentheses

Easy · Stacks & Monotonic Stack · step through it in Java, Python and C++ on your own input

Check that every bracket is closed by the right kind, in the right order, with a stack of open brackets.

Problem

Given a string s of the characters (, ), [, ], { and }, decide whether it is valid: every open bracket is closed by a bracket of the same type, open brackets are closed in the correct order, and every closer has a matching open bracket.

Constraints

Edge cases to test

Follow-up questions

What if there is only one bracket type?
A counter replaces the stack: +1 for (, −1 for ), never below 0, ending at 0. O(1) space.
How do you find the longest valid substring?
Push indices and keep the last unmatched position on the stack; each match gives a length i − top (LC 32): O(n).
What is the fewest removals to make it valid?
Count unmatched openers and closers in one pass: their total is the answer (LC 1249 builds the string).

Solution

Java

public boolean isValid(String s) {
    Map<Character, Character> pairs = Map.of(')', '(', ']', '[', '}', '{');
    Deque<Character> stack = new ArrayDeque<>();
    for (char c : s.toCharArray()) {
        if (!pairs.containsKey(c)) stack.push(c);
        else if (stack.isEmpty() || !pairs.get(c).equals(stack.pop()))
            return false;
    }
    return stack.isEmpty();
}

Python

def is_valid(s):
    pairs = {')': '(', ']': '[', '}': '{'}
    stack = []
    for c in s:
        if c not in pairs: stack.append(c)
        elif not stack or stack.pop() != pairs[c]:
            return False
    return not stack

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    bool isValid(string &s) {
        unordered_map<char, char> pairs = {{')', '('}, {']', '['}, {'}', '{'}};
        deque<char> stack = {};
        for (char c : s) {
            if (!pairs.count(c))
                stack.push_back(c);
            else if (stack.empty() || pairs[c] != stack.back())
                return false;
            else
                stack.pop_back();
        }
        return stack.empty();
    }
};

More Stacks & Monotonic Stack problems