Easy Stack ⭐ Classic Interview

Valid Parentheses — Stack Solution (Python, C, JavaScript)

Problem Statement

Given string s of '()[]{}'characters, determine if the brackets are opened and closed in the correct order.

Example
Input: s = "()[]{}"
Output: true
Time Complexity
O(n)
Space Complexity
O(n)

The Intuition

LIFO Stack — push open brackets. When a closing bracket is seen, pop the top and check if it matches.

Solution Code

def isValid(s):
    stack = []
    match = {")": "(", "}": "{", "]": "["}
    for c in s:
        if c in match:
            if stack and stack[-1] == match[c]:
                stack.pop()
            else:
                return False
        else:
            stack.append(c)
    return len(stack) == 0
bool isValid(char* s) {
    int n = strlen(s);
    if (n % 2) return false;
    char stack[n]; int top = -1;
    for (int i = 0; i < n; i++) {
        char c = s[i];
        if (c=="("||c=="{"||c=="[") stack[++top]=c;
        else {
            if (top<0) return false;
            char t = stack[top--];
            if((c==")"&&t!="(")||(c=="}"&&t!="{")||(c=="]"&&t!="[")) return false;
        }
    }
    return top == -1;
}
function isValid(s) {
    const stack = [], map = {")":"(","}":"{","]":"["};
    for (const c of s) {
        if (c in map) {
            if (stack.length && stack.at(-1) === map[c]) stack.pop();
            else return false;
        } else stack.push(c);
    }
    return !stack.length;
}

Frequently Asked Questions

Q: Why a Stack?
Brackets must close in reverse order of opening — exactly the Last-In-First-Out (LIFO) behaviour of a stack.

Practice These Problems in a Real Curriculum

DoxaTech Hub's 10-month programme covers Data Structures, Algorithms, Python, C, SQL, and Full-Stack Development through 40 weeks of real, graded projects.

Get Started → More Problems