The Wayback Machine - https://web.archive.org/web/20241008142920/https://www.geeksforgeeks.org/check-for-balanced-parentheses-in-an-expression/
Open In App

Valid Parentheses in an Expression

Last Updated : 16 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given an expression string s, write a program to examine whether the pairs and the orders of “{“, “}”, “(“, “)”, “[“, “]” are correct in the given expression.

Example: 

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

Input: s = “[(])” 
Output: false
Explanation: 1 and 4 brackets are not balanced because 
there is a closing ‘]’ before the closing ‘(‘

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

The idea is to put all the opening brackets in the stack. Whenever you hit a closing bracket, search if the top of the stack is the opening bracket of the same nature. If this holds then pop the stack and continue the iteration. In the end if the stack is empty, it means all brackets are balanced or well-formed. Otherwise, they are not balanced.

Step-by-step approach:

  • Declare a character stack (say temp).
  • Now traverse the string exp. 
    • If the current character is a starting bracket ( ‘(‘ or ‘{‘  or ‘[‘ ) then push it to stack.
    • If the current character is a closing bracket ( ‘)’ or ‘}’ or ‘]’ ) then pop from the stack and if the popped character is the matching starting bracket then fine.
    • Else brackets are Not Balanced.
  • After complete traversal, if some starting brackets are left in the stack then the expression is Not balanced, else Balanced.

Illustration:

Below is the implementation of the above approach:

C++
// C++ program to check for balanced brackets.
#include <bits/stdc++.h>
using namespace std;

// Function to check if brackets are balanced
bool ispar(const string& s) {  // Pass string by reference
  
    // Declare a stack to hold the previous brackets.
    stack<char> stk;
    for (int i = 0; i < s.length(); i++) {
        
        // Check if the character is an opening bracket
        if (s[i] == '(' || s[i] == '{' || s[i] == '[') {
            stk.push(s[i]); 
        } 
      
        else {
            // If it's a closing bracket, check if the stack is non-empty
            // and if the top of the stack is a matching opening bracket
            if (!stk.empty() && 
                ((stk.top() == '(' && s[i] == ')') ||
                 (stk.top() == '{' && s[i] == '}') ||
                 (stk.top() == '[' && s[i] == ']'))) {
                stk.pop(); // Pop the matching opening bracket
            }
            else {
                return false; // Unmatched closing bracket
            }
        }
    }
    
    // If stack is empty, return true (balanced), otherwise false
    return stk.empty();
}

int main() {
  
    string s = "{()}[]";

    // Function call
    if (ispar(s))
        cout << "true";
    else
        cout << "false";
    return 0;
}
C
// C program to check for balanced brackets.
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>

#define MAX 100

// Stack structure definition
typedef struct {
    char arr[MAX];
    int top;
} Stack;

// Initialize stack
void init(Stack *s) {
    s->top = -1;
}

// Check if stack is empty
bool isEmpty(Stack *s) {
    return s->top == -1;
}

// Push element onto stack
void push(Stack *s, char c) {
    s->arr[++(s->top)] = c;
}

// Pop element from stack
char pop(Stack *s) {
    return s->arr[(s->top)--];
}

// Peek top element of stack
char peek(Stack *s) {
    return s->arr[s->top];
}

// Check if brackets are balanced
bool ispar(const char *s) {
    Stack stk;
    init(&stk);

    for (int i = 0; s[i] != '\0'; i++) {
        char ch = s[i];

        if (isEmpty(&stk)) {
            // Stack is empty, push the current bracket
            push(&stk, ch);
        } else if ((peek(&stk) == '(' && ch == ')') ||
                   (peek(&stk) == '{' && ch == '}') ||
                   (peek(&stk) == '[' && ch == ']')) {
            // Found a complete pair of brackets, pop it
            pop(&stk);
        } else {
            // Push current bracket onto stack
            push(&stk, ch);
        }
    }

    // If stack is empty, brackets are balanced
    return isEmpty(&stk);
}

int main() {
    const char *s = "{()}[]";

    // Function call to check for balanced brackets
    if (ispar(s)) {
        printf("true\n");
    } else {
        printf("false\n");
    }

    return 0;
}
Java
import java.util.Stack;

// Function to check if brackets are balanced
public class Main {
    public static boolean ispar(String s) {  
        // Declare a stack to hold the previous brackets.
        Stack<Character> stk = new Stack<>();
        for (int i = 0; i < s.length(); i++) {
          
            // Check if the character is an opening bracket
            if (s.charAt(i) == '(' || s.charAt(i) == '{' || s.charAt(i) == '[') {
                stk.push(s.charAt(i)); 
            } 
            else {
              
                // If it's a closing bracket, check if the stack is non-empty
                // and if the top of the stack is a matching opening bracket
                if (!stk.empty() && 
                    ((stk.peek() == '(' && s.charAt(i) == ')') ||
                     (stk.peek() == '{' && s.charAt(i) == '}') ||
                     (stk.peek() == '[' && s.charAt(i) == ']'))) {
                    stk.pop(); 
                }
                else {
                    return false; // Unmatched closing bracket
                }
            }
        }
      
        // If stack is empty, return true (balanced), 
        // otherwise false
        return stk.empty();
    }

    public static void main(String[] args) {
        String s = "{()}[]";
        if (ispar(s))
            System.out.println("true");
        else
            System.out.println("false");
    }
}
Python
# retain comments in py code
def ispar(s):
    stack = []
    for char in s:
      
        # Opening bracket
        if char in '({[':
            stack.append(char)
            
        # Closing Bracket    
        elif char in ')}]':
          
            # closing bracket without opening
            if not stack:
                return False
              
            # Else pop an item check for matching  
            top = stack.pop()
            if (top == '(' and char != ')') or \
               (top == '{' and char != '}') or \
               (top == '[' and char != ']'):
                return False
              
    # If an opening bracket without closing          
    return len(stack) == 0

s = '{()}[]'

if ispar(s):
    print("true")
else:
    print("false")
CSharp
using System;
using System.Collections.Generic;

// Function to check if brackets are balanced
public class Main {
    public static bool Ispar(string s) {  
      
        // Declare a stack to hold the previous brackets.
        Stack<char> stk = new Stack<char>();
        for (int i = 0; i < s.Length; i++) {
          
            // Check if the character is an opening bracket
            if (s[i] == '(' || s[i] == '{' || s[i] == '[') {
                stk.Push(s[i]); 
            } 
            else {
              
                // If it's a closing bracket, check if the stack is non-empty
                // and if the top of the stack is a matching opening bracket
                if (stk.Count > 0 && 
                    ((stk.Peek() == '(' && s[i] == ')') ||
                     (stk.Peek() == '{' && s[i] == '}') ||
                     (stk.Peek() == '[' && s[i] == ']'))) {
                    stk.Pop(); 
                }
                else {
                    return false; // Unmatched closing bracket
                }
            }
        }
      
        // If stack is empty, return true (balanced), 
        // otherwise false
        return stk.Count == 0;
    }

    public static void Main(string[] args) {
        string s = "{()}[]";
        if (Ispar(s))
            Console.WriteLine("true");
        else
            Console.WriteLine("false");
    }
}
JavaScript
// JavaScript program to check for balanced brackets.
function ispar(s) {

    // Declare a stack to hold the previous brackets.
    let stk = [];
    for (let i = 0; i < s.length; i++) {
    
        // Check if the character is an opening bracket
        if (s[i] === '(' || s[i] === '{' || s[i] === '[') {
            stk.push(s[i]);
        } else {
        
            // If it's a closing bracket, check if the stack is non-empty
            // and if the top of the stack is a matching opening bracket
            if (stk.length > 0 &&
                ((stk[stk.length - 1] === '(' && s[i] === ')') ||
                 (stk[stk.length - 1] === '{' && s[i] === '}') ||
                 (stk[stk.length - 1] === '[' && s[i] === ']'))) {
                stk.pop(); // Pop the matching opening bracket
            } else {
                return false; // Unmatched closing bracket
            }
        }
    }
    
    // If stack is empty, return true (balanced), otherwise false
    return stk.length === 0;
}

let s = "{()}[]";

// Function call
console.log(ispar(s) ? "true" : "false");

Output
true

Time Complexity: O(n), Iteration over the string of size n one time.
Auxiliary Space: O(n), for the stack.

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

Instead of using actual Stack, we can uses the input string s itself to simulate stack behavior. We can use a top variable to keep track of the “top” of this virtual stack. This approach makes use of the existing string to avoid the need for additional memory to store stack elements.

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

Step-by-step approach:

  • Initialize top = -1 to represent an empty stack.
  • Traverse over the given string and for each character:
    • If top is -1 or the current character doesn’t match the top, increment top and store the character at s[top].
    • If the current character matches s[top], decrement top to remove the last unmatched opening parenthesis.
  • After processing, if top is -1, the string is balanced. Otherwise, it is unbalanced.

Below is the implementation of the above approach:

C++
#include <bits/stdc++.h>
using namespace std;

// Check if characters match
bool checkMatch(char c1, char c2){
    if (c1 == '(' && c2 == ')') return true;
    if (c1 == '[' && c2 == ']') return true;
    if (c1 == '{' && c2 == '}') return true;
    return false;
}

// Check if parentheses are balanced
bool ispar(string s){
  
    // Initialize top to -1 (empty stack simulation)
    int top = -1;
    for (int i = 0; i < s.length(); ++i){
      
        // Push char if stack is empty or no match
        if (top < 0 || !checkMatch(s[top], s[i])){
            ++top;
            s[top] = s[i];
        }
        else{
          
            // Pop from stack if match found
            --top;
        }
    }
  
    // Return true if stack is empty (balanced)
    return top == -1;
}

int main(){
    string s = "{()}[]";
    cout << (ispar(s) ? "true" : "false") << endl;
    return 0;
}
C
#include <stdio.h>
#include <stdbool.h>
#include <string.h>

// Check if characters match
bool checkMatch(char c1, char c2){
    if (c1 == '(' && c2 == ')') return true;
    if (c1 == '[' && c2 == ']') return true;
    if (c1 == '{' && c2 == '}') return true;
    return false;
}

// Check if parentheses are balanced
bool ispar(char s[]){
  
    // Initialize top as -1 (empty stack simulation)
    int top = -1;
    for (int i = 0; i < strlen(s); ++i){
      
        // Push char if stack is empty or no match
        if (top < 0 || !checkMatch(s[top], s[i])){
            ++top;
            s[top] = s[i];
        }
        else{
          
            // Pop from stack if match found
            --top;
        }
    }
  
    // Return true if stack is empty (balanced)
    return top == -1;
}

int main(){
    char s[] = "{()}[]";
    printf("%s\n", ispar(s) ? "true" : "false");
    return 0;
}

Output
true

Time Complexity: O(n), Iteration over the string of size n.
Auxiliary Space: O(1), no extra space used



Previous Article
Next Article

Similar Reads

Count pairs of parentheses sequences such that parentheses are balanced
Given N bracket sequences, the task is to find the number of pairs of bracket sequences by joining which can be obtained a balanced bracket sequence as a whole. A bracket parentheses sequence can only be a part of a single pair. Examples: Input: { ")())", ")", "((", "((", "(", ")", ")"} Output: 2 Bracket sequence {1, 3} and {5, 6} Input: {"()", "((
9 min read
Minimum number of Parentheses to be added to make it valid
Given a string S of parentheses '(' or ')' where, [Tex]0\leq len(S)\leq 1000 [/Tex]. The task is to find a minimum number of parentheses '(' or ')' (at any positions) we must add to make the resulting parentheses string is valid. Examples: Input: str = "())" Output: 1 One '(' is required at beginning. Input: str = "(((" Output: 3 Three ')' is requi
9 min read
Find the number of valid parentheses expressions of given length
Given a number n find the number of valid parentheses expressions of that length. Examples : Input: 2 Output: 1 There is only possible valid expression of length 2, "()" Input: 4 Output: 2 Possible valid expression of length 4 are "(())" and "()()" Input: 6 Output: 5 Possible valid expressions are ((())), ()(()), ()()(), (())() and (()()) This is m
9 min read
Longest Valid Parentheses Substring
Given a string str consisting of opening and closing parenthesis '(' and ')'. Find the length of the longest valid parenthesis substring. Examples: Input: ((()Output : 2Explanation : Longest Valid Parentheses Substring is (). Input: )()())Output : 4Explanation: Longest Valid Parentheses Substring is ()() . Table of Content [Expected Approach - 1] U
15+ min read
Check for balanced parentheses in an expression | O(1) space
Given a string of length n having parentheses in it, your task is to find whether given string has balanced parentheses or not. Please note there is constraint on space i.e. we are allowed to use only O(1) extra space. Also See : Check for balanced parentheses Examples: Input : (())[] Output : Yes Input : ))(({}{ Output : No If k = 1, then we will
15+ min read
Arrange given numbers in a mathematical expression using operators [+, -, *, /] and parentheses to get value 24
Given an array arr[] consisting of 4 integers each between [1-9], the task is to check whether it is possible to get the number 24 by placing the operators +, -, /, and * between the numbers or grouping them using parenthesis. If it is possible then print "Possible", Otherwise print "Not Possible". Examples: Input: arr[] = {3, 6, 8, 2}Output: Possi
11 min read
Find a valid parenthesis sequence of length K from a given valid parenthesis sequence
Given a string S of valid parentheses sequence of length N and an even integer K, the task is to find the valid parentheses sequence of length K which is also a subsequence of the given string. Note: There can be more than one valid sequence, print any of them. Examples: Input: S = "()()()", K = 4Output: ()()Explanation:The string "()()" is a subse
7 min read
How to check Aadhaar number is valid or not using Regular Expression
Given string str, the task is to check whether the given string is a valid Aadhaar number or not by using Regular Expression. The valid Aadhaar number must satisfy the following conditions: It should have 12 digits.It should not start with 0 and 1.It should not contain any alphabet and special characters.It should have white space after every 4 dig
5 min read
Check if an URL is valid or not using Regular Expression
Given a URL as a character string str of size N.The task is to check if the given URL is valid or not.Examples : Input : str = "https://www.geeksforgeeks.org/" Output : Yes Explanation : The above URL is a valid URL.Input : str = "https:// www.geeksforgeeks.org/" Output : No Explanation : Note that there is a space after https://, hence the URL is
4 min read
Maximum value of expression (arr[i] + arr[j] * arr[k]) formed from a valid Triplet
Given an array arr[] of N integers. The task is to find the maximum value of (arr[i] + arr[j] * arr[k]) among every triplet (i, j, k) such that arr[i] < arr[j] < arr[k] and i < j < k. If there doesn't exist any such triplets then print “-1". Examples: Input: arr[]={7, 9, 3, 8, 11, 10}Output: 106Explanation:The valid triplets are:1) (7,
14 min read
Valid file extension checker using Regular Expression
Given string str, the task is to check whether the given string is a valid file extension or not by using Regular Expression. The valid file extension must specify the following conditions: It should start with a string of at least one character.It should not have any white space.It should be followed by a dot(.).It should end with any one of the f
7 min read
Check if a given string is a valid number (Integer or Floating Point) in Java | SET 2 (Regular Expression approach)
In Set 1, we have discussed general approach to check whether a string is a valid number or not. In this post, we will discuss regular expression approach to check for a number. Examples: Input : str = "11.5" Output : true Input : str = "abc" Output : false Input : str = "2e10" Output : true Input : 10e5.4 Output : false Check if a given string is
3 min read
Convert Infix expression to Postfix expression
Write a program to convert an Infix expression to Postfix form. Infix expression: The expression of the form "a operator b" (a + b) i.e., when an operator is in-between every pair of operands.Postfix expression: The expression of the form "a b operator" (ab+) i.e., When every pair of operands is followed by an operator. Examples: Input: A + B * C +
13 min read
Pairs involved in Balanced Parentheses
Given a string of brackets, the task is to find the number of pairs of brackets involved in a balanced sequence in a given range. Examples : Input : ((())(() Range : 1 5 Range : 3 8 Output : 2 2 Explanation : In range 1 to 5 ((()), there are the two pairs. In range 3 to 8 ()) ((), there are the two pairs. Input : )()())) Range : 1 2 Range : 4 7 Out
14 min read
Cost to Balance the parentheses
Parentheses are said to be balanced when every opening brace has a closing brace like "()()" or "(())" or "(()())" etc. Incorrect balancing includes ")(" or "))((" etc. The task here is to correct the sequence of parentheses in such a way that it is done in minimum cost. And shifting of parentheses by over one parentheses costs 1. If the parenthese
7 min read
Number of balanced parentheses substrings
Given a balanced parentheses string which consists of '(' and ')'. The task is to find the number of balanced parentheses substrings in the given string Examples : Input : str = "()()()" Output : 6 (), (), (), ()(), ()(), ()()()Input : str = "(())()" Output : 4 (), (()), (), (())() Approach : Let us assume that whenever we encounter with opening br
6 min read
Number of ways to insert two pairs of parentheses into a string of N characters
Given a string str of length N, the task is to find the number of ways to insert only 2 pairs of parentheses into the given string such that the resultant string is still valid.Examples: Input: str = "ab" Output: 6 ((a))b, ((a)b), ((ab)), (a)(b), (a(b)), a((b)) which are a total of 6 ways.Input: str = "aab" Output: 20 Approach: it can be observed t
3 min read
Check if the Depth of Parentheses is correct in the given String
Given a string S consisting of opening parentheses, closing parentheses and integers, the task is to print Yes if, in this string, the integers correctly indicates its depth. Depth refers to the number of nested sets of parentheses surrounding that integer. Print No otherwise.Examples: Input: S = "((2)((3)))" Output: Yes Explanation: No of Opening
7 min read
Insert minimum parentheses to make string balanced
Given a string of digits S. The task is to insert a minimum number of opening and closing parentheses into the string S such that the resulting string is balanced and each digit d must be inside d pairs of matching parentheses. Examples: Input: S = 221 Output: ((22)1) Explanation: The string ((2))((2))(1) is not valid solutions because it is not of
6 min read
Balance the parentheses for the given number N
Given a number N, the task is to insert the minimum number of opening and closing parenthesis into the number N such that the resultant string is balanced and every digit D is exactly in D pairs of matching parenthesis. Examples: Input: N = 312 Output: (((3))1(2)) Explanation: Every digit in the number is within exactly in D parenthesis. There are
3 min read
Reduce string by removing outermost parentheses from each primitive substring
Given a string S of valid parentheses "(" and ")", the task is to print the string obtained by removing the outermost parentheses of every primitive substring from S. A valid parentheses substring S is primitive if it is non-empty, and cannot be split into two or more non-empty substrings which are also a valid parentheses. Examples: Input: S = "((
9 min read
Print the string obtained after removal of outermost parentheses
Given a valid parenthesis string str consisting of lowercase alphabets, opening, and closing brackets, the task is to find the string by removing the outermost enclosing brackets such that the string remains a valid parenthesis string. Examples: Input: S = "(((a)(bcd)(e)))"Output: (a)(bcd)(e)Explanation: The outermost enclosing brackets are: { S[0]
8 min read
Calculate score of a string consisting of balanced parentheses
Given a string str consisting of pairs of balanced parentheses, the task is to calculate the score of the given string based on the following rules: "()" has a score of 1."x y" has a score of x + y where x and y are individual pairs of balanced parentheses."(x)" has a score twice of x (i.e), 2 * score of x. Examples: Input: str = "()()"Output: 2Exp
7 min read
Number of levels having balanced parentheses in a Binary Tree
Given a Binary Tree consisting only '(' and ')' a level is considered to be balanced if the nodes of the level having parenthesis are balanced from left to right. The task is to count the total number of balanced levels in a binary tree. Examples: Input: ( / \ ( ) / \ \ ( ) ( / \ \ \ ( ( ) ) Output: 2Explanation:In Level 2 and 4, the parenthesis ar
10 min read
Calculate score of parentheses from a given string
Given string str of length N, consisting of pairs of balanced parentheses, the task is to calculate the score of the given string based on the given rules: “()” has a score of 1.“a b” has a score of a + b, where a and b are individual pairs of balanced parentheses.“(a)” has a score twice of a i.e., the score is 2 * score of a. Examples: Input: str
6 min read
Modify a numeric string to a balanced parentheses by replacements
Given a numeric string S made up of characters '1', '2' and '3' only, the task is to replace characters with either an open bracket ( '(' ) or a closed bracket ( ')' ) such that the newly formed string becomes a balanced bracket sequence. Note: All occurrences of a character must be replaced by the same parentheses. Examples: Input: S = "1123"Outpu
10 min read
Remove Invalid Parentheses
An expression will be given which can contain open and close parentheses and optionally some characters, No other operator will be there in string. We need to remove minimum number of parentheses to make the input string valid. If more than one valid output are possible removing same number of parentheses then print all such output. Examples: Input
9 min read
Length of longest balanced parentheses prefix
Given a string of open bracket '(' and closed bracket ')'. The task is to find the length of longest balanced prefix. Examples: Input : S = "((()())())((" Output : 10From index 0 to index 9, they are forming a balanced parentheses prefix.Input : S = "()(())((()"Output : 6 The idea is take value of open bracket '(' as 1 and value of close bracket ')
9 min read
Print all combinations of balanced parentheses
Given a number n, the task is to generate all possible n pairs of balanced parentheses. Examples: Input: n=1Output: {}Explanation: This the only sequence of balanced parenthesis formed using 1 pair of balanced parenthesis. Input : n=2Output: {}{} {{}}Explanation: This the only two sequences of balanced parenthesis formed using 2 pair of balanced pa
12 min read
Check if a king can move a valid move or not when N nights are there in a modified chessboard
Given an infinite chessboard with the same rules as that of chess. Also given are N knights coordinates on the infinite chessboard(-10^9 <= x, y <= 10^9) and the king's coordinate, the task is to check if the King is checkmate or not. Examples: Input: a[] = { {1, 0}, {0, 2}, {2, 5}, {4, 4}, {5, 0}, {6, 2} } king -> {3, 2} Output: Yes The k
10 min read