Code Logo

Balanced Parentheses

Published at25 Jul 2026
Medium 0 views
Like0

Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. A string is valid if brackets are closed in the correct order by the same type, and every closing bracket has a corresponding opening bracket of the same type.

Use a stack data structure. Iterate through each character. If it's an opening bracket, push it onto the stack. If it's a closing bracket, check if the stack is empty or if the top of the stack doesn't match the corresponding opening bracket — if either is true, return false. After processing all characters, return true if the stack is empty.

This classic problem tests understanding of stack-based parsing. Time complexity is O(n) and space complexity is O(n) for the stack in the worst case.

Example Input & Output

Example 1
Input
"()"
Output
true
Explanation

Simple parentheses balanced

Example 2
Input
"([)]"
Output
false
Explanation

Incorrect nesting

Example 3
Input
""
Output
true
Explanation

Empty string

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

Multiple bracket types

Example 5
Input
"(]"
Output
false
Explanation

Mismatched brackets

Algorithm Flow

Recommendation Algorithm Flow for Balanced Parentheses
Recommendation Algorithm Flow for Balanced Parentheses

Solution Approach

function solution(s) {
  var stack = [];
  var map = {')': '(', '}': '{', ']': '['};
  for (var i = 0; i < s.length; i++) {
    var c = s.charAt(i);
    if (c === '(' || c === '{' || c === '[') {
      stack.push(c);
    } else {
      if (stack.length === 0 || stack.pop() !== map[c]) return false;
    }
  }
  return stack.length === 0;
}

Best Answers

java
class Solution {
    public boolean solution(String s) {
        java.util.Stack<Character> st=new java.util.Stack<>();
        for(int i=0;i<s.length();i++){char c=s.charAt(i);
            if(c=='('||c=='{'||c=='[')st.push(c);
            else if(st.isEmpty())return false;
            else if(c==')'&&st.pop()!='(')return false;
            else if(c=='}'&&st.pop()!='{')return false;
            else if(c==']'&&st.pop()!='[')return false;
        }return st.isEmpty();
    }
}