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

Solution Approach

Check if a string containing only parentheses '()' is balanced. Use a counter: increment for '(', decrement for ')'. If the counter ever goes negative, return false. If the counter is zero at the end, the string is balanced.

function isBalanced(s) {
  var count = 0;
  for (var i = 0; i < s.length; i++) {
    if (s[i] === '(') count++;
    else if (s[i] === ')') { count--; if (count < 0) return false; }
  }
  return count === 0;
}

A negative count means more closing than opening parentheses at that point, which cannot be fixed later. A non-zero count at the end means unclosed opening parentheses remain.

Time complexity is O(n), space complexity is O(1).

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();
    }
}