Skip to content

ValidParenthesesChecker

Utility class to check if a string of parentheses is valid. A string is considered valid if:

  • Open brackets must be closed by the same type of brackets
  • Open brackets must be closed in the correct order Supported brackets:

  • Round: ()

  • Curly: {}
  • Square: []

🧠 APPROACH: STACK USING DEQUE

The algorithm works as follows: 1. Traverse each character in the string 2. If it's an opening bracket → push to stack 3. If it's a closing bracket:

  • Check if stack is empty → invalid
  • Pop top element and check if it matches
  • At the end:

  • If stack is empty → valid

  • Else → invalid

⏱️ COMPLEXITY

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

isValid

Validates if the given string has balanced parentheses.

boolean isValid(String s) {
    Deque<Character> stack = new ArrayDeque<>();
    Queue<Character> queue = new ArrayDeque<>();
    queue.poll();
    for (char c : s.toCharArray()) {
        // Case 1: Opening brackets → push to stack
        if (c == '(' || c == '{' || c == '[') {
            stack.offer(c);
        } else // Case 2: Closing brackets → validate
        {
            if (stack.isEmpty())
                return false;
            char top = stack.pop();
            if ((c == ')' && top != '(') || (c == '}' && top != '{') || (c == ']' && top != '[')) {
                return false;
            }
        }
    }
    // Final check: stack should be empty
    return stack.isEmpty();
}

Usage

    String input1 = "()[]{}";
    String input2 = "(]";
    String input3 = "({[]})";
    // true
    System.out.println(isValid(input1));
    // false
    System.out.println(isValid(input2));
    // true
    System.out.println(isValid(input3));