Valid Parentheses


20. Valid Parentheses – LeetCode


Problem Statement

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

A string is valid if:

  1. Open brackets are closed by the same type of brackets.

  2. Open brackets are closed in the correct order.


Examples

Example 1:

Input: s = "()"
Output: true

Example 2:

Input: s = "()[]{}"
Output: true

Example 3:

Input: s = "(]"
Output: false

Constraints


Intuition

The problem is based on balanced brackets. A valid parentheses string must maintain:

A stack is ideal for this, because it follows Last-In-First-Out (LIFO) behavior:


Approach: Stack-Based Matching

  1. Traverse the input string character by character.

  2. If the character is an opening bracket, push it to the stack.

  3. If it's a closing bracket:

    • Check if the stack is empty → if yes, return false.

    • Check the top of the stack:

      • If it's a matching opening bracket, pop it.

      • If not, return false.

  4. After the loop, return true only if the stack is empty (all brackets matched).


Java Code

class Solution {
    public boolean isValid(String s) {
        if (s.charAt(0) == '}' || s.charAt(0) == ')' || s.charAt(0) == ']') return false;

        Stack<Character> stack = new Stack<>();
        for (int i = 0; i < s.length(); i++) {
            char ch = s.charAt(i);
            
            if (ch == '(' || ch == '{' || ch == '[') {
                stack.push(ch);
            } else {
                if (stack.isEmpty()) return false;
                
                char top = stack.peek();
                if ((ch == ')' && top == '(') ||
                    (ch == ']' && top == '[') ||
                    (ch == '}' && top == '{')) {
                    stack.pop();
                } else {
                    return false;
                }
            }
        }
        return stack.isEmpty();
    }
}

Time and Space Complexity

Metric Value
Time Complexity O(n)
Space Complexity O(n)
Explanation Stack holds at most n characters in worst case

Dry Run

Input:

s = "{[()]}"

Stack State:

Stack is empty → valid.

Output:

true

Follow-Up

To generalize or optimize:


Conclusion

This problem is a foundational example of stack-based validation, especially useful in: