Code Logo

Valid Parentheses Grouping

Published at23 Jul 2026
Easy 23 views
Like0

You are given a string containing only the characters (, ), {, }, [, and ]. Your task is to determine whether the brackets are correctly matched and nested.

A string is valid if every opening bracket has a matching closing bracket of the same type, and they close in the correct order. This is exactly the kind of problem where a stack is the natural choice because it follows the last-in-first-out (LIFO) principle: the most recently opened bracket must be the first one to close.

For example, ()[] is valid because each opening bracket is immediately closed by the correct type. But (] is invalid because ( expects ) but finds ] instead. The tricky case is ([)] which is invalid because the [ was opened after ( but closed before it. Proper nesting requires brackets to close in reverse order of opening.

Your function should return true if the string is valid and false otherwise.

Example Input & Output

Example 1
Input
{[]}
Output
true
Explanation

Correctly nested brackets.

Example 2
Input
(]
Output
false
Explanation

Mismatched closing bracket.

Example 3
Input
()
Output
true
Explanation

Simple pair of parentheses.

Example 4
Input
()[]{}
Output
true
Explanation

Multiple different bracket types in sequence.

Example 5
Input
([)]
Output
false
Explanation

Nested incorrectly: closing bracket does not match the most recent opening bracket.

Algorithm Flow

Recommendation Algorithm Flow for Valid Parentheses Grouping
Recommendation Algorithm Flow for Valid Parentheses Grouping

Solution Approach

The stack is the perfect data structure for bracket matching because it naturally tracks the most recently opened bracket. When you encounter an opening bracket, push it onto the stack. When you encounter a closing bracket, check that it matches the bracket on top of the stack. If it matches, pop the stack and continue. If it does not match or the stack is empty, the string is invalid.

At the end of the string, the stack must be empty for the string to be valid. If any brackets remain unclosed, the string is invalid.

function solution(s) {
  const stack = []
  const pairs = {')': '(', '}': '{', ']': '['}
  for (const ch of s) {
    if (ch in pairs) {
      if (!stack.length || stack.pop() !== pairs[ch]) return false
    } else {
      stack.push(ch)
    }
  }
  return stack.length === 0
}

The time complexity is O(n) because we process each character once. The space complexity is O(n) in the worst case when all characters are opening brackets.

Best Answers

java
import java.util.*;
class Solution {
    public boolean solution(String s) {
        Stack<Character> stack = new Stack<>();
        Map<Character, Character> pairs = new HashMap<>();
        pairs.put(')', '(');
        pairs.put('}', '{');
        pairs.put(']', '[');
        for (char ch : s.toCharArray()) {
            if (pairs.containsKey(ch)) {
                if (stack.isEmpty() || stack.pop() != pairs.get(ch)) return false;
            } else {
                stack.push(ch);
            }
        }
        return stack.isEmpty();
    }
}