Valid Parentheses Grouping
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
Correctly nested brackets.
Mismatched closing bracket.
Simple pair of parentheses.
Multiple different bracket types in sequence.
Nested incorrectly: closing bracket does not match the most recent opening bracket.
Algorithm Flow

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.
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
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();
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
