VOOZH about

URL: https://www.geeksforgeeks.org/dsa/check-for-balanced-parentheses-in-an-expression/

⇱ Valid Parentheses in an Expression - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Valid Parentheses in an Expression

Last Updated : 17 Sep, 2025

Given a string s containing three types of brackets {}, () and []. Determine whether the Expression are balanced or not.
An expression is balanced if each opening bracket has a corresponding closing bracket of the same type, the pairs are properly ordered and no bracket closes before its matching opening bracket.

  • Balanced: "[()()]{}" → every opening bracket is closed in the correct order.
  • Not balanced: "([{]})" → the ']' closes before the matching '{' is closed, breaking the nesting rule.

Example

Input: s = "[{()}]"
Output: true
Explanation: All the brackets are well-formed.

Input: s = "([{]})"
Output: false
Explanation: The expression is not balanced because there is a closing ']' before the closing '}'.

[Approach 1] Using Stack - O(n) Time and O(n) Space

We use a stack to ensure that every opening has a matching closing. Each opening is pushed onto the stack. When a closing appears, we check if the stack has a corresponding opening to pop; if not, the string is unbalanced. After processing the entire string, the stack must be empty for it to be considered balanced.

Illustration:



Output
true

[Approach 2] Without using Stack - O(n) Time and O(1) Space

Instead of using an external stack, we can simulate stack operations directly on the input string by modifying it in place. A variable top is used to track the index of the last unmatched opening bracket. Whenever an opening bracket is found, it is placed at the next top position. For a closing bracket, we check if it matches the character at top. If it does, we simply decrement top; otherwise, the string is unbalanced. In the end, if top is -1, all brackets are matched and the string is balanced.

Note: Strings are immutable in Java, Python, C#, and JavaScript. Therefore, we cannot modify them in place, making this approach unsuitable for these languages.


Output
true
Comment