</>

20. Valid Parentheses

Easy NeetCode 150
Stack Time O(n) Space O(n)
↗ Open on LeetCode Source: NeetCode 150

Quick review

Pattern
Stack
Time
O(n)
Space
O(n)

Standard Solution (C++)

SummaryGiven a string containing only bracket characters ('(', ')', '{', '}', '[', ']'), determine whether every opening bracket is closed by a matching bracket type in the correct nested order.

Approach
  • Use a stack to track what closing bracket is expected next: push the expected closer whenever an opener is encountered.
  • When a closing bracket is seen, check that the stack is non-empty and its top matches the current character; if not, the string is invalid.
  • This works because valid nesting is LIFO — the most recently opened bracket must be closed first.
  • After processing all characters, the string is valid only if the stack is empty (no unmatched openers remain).
#include <string>
#include <stack>
#include <unordered_map>
using namespace std;

class Solution {
public:
    bool isValid(string s) {
        // Maps each opener to its expected closer
        unordered_map<char, char> match = {
            {'(', ')'},
            {'{', '}'},
            {'[', ']'}
        };

        stack<char> st;
        for (char c : s) {
            if (match.count(c)) {
                // Push the expected closing bracket
                st.push(match[c]);
            } else {
                // Closer must match the top of the stack
                if (st.empty() || st.top() != c)
                    return false;
                st.pop();
            }
        }

        // Valid only if all openers were matched
        return st.empty();
    }
};
Time O(n) Space O(n)

A canonical reference solution. Problem statement © LeetCode — see the official link above.

My Solution (C++)

class Solution {
public:
    bool isValid(string s) {
        vector<char> stack; // we can also use stack<char>
        for(char c: s){
            if(c=='('){
                stack.push_back(')');
            }
            else if(c=='{'){
                stack.push_back('}');
            }
            else if(c=='['){
                stack.push_back(']');
            }
            else{
                if(stack.empty() || stack.back()!=c)
                    return false;
                stack.pop_back();
            }
        }
        
        return stack.empty();
    }
};

// Time Complexity: O(n)
// Space Complexity: O(n)
Time O(n) Space O(n)

My own solution and notes, as I wrote them.

▶ Run it — editable in-browser playground with a sample driver C++

Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.

C++ ▶ Runnable Auto-generated driver with sample input — unverified.

Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.

Related — same pattern