Junior Detailed answer Stacks DSA & Coding Interviews

How do you validate parentheses with a stack?

Short answer: Push opening brackets. On a closing bracket, pop and check it matches. At the end the stack must be empty. Covers (), {}, [] in one pass.

Sample solution

C#
bool IsValid(string s) {
    var st = new Stack<char>();
    foreach (char c in s) {
        if (c is '(' or '[' or '{') st.Push(c);
        else {
            if (st.Count == 0) return false;
            char o = st.Pop();
            if ((c == ')' && o != '(') || (c == ']' && o != '[') || (c == '}' && o != '{'))
                return false;
        }
    }
    return st.Count == 0;
}

Complexity

Time O(n), Space O(n).

Edge cases to mention

  • Empty string → true
  • Only closers
  • Nested mixed types

Common follow-ups

  • Longest valid parentheses
  • Minimum remove to make valid
  • Generate parentheses
This is a common phone-screen opener — nail it quickly and cleanly.
Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details