The Wayback Machine - https://web.archive.org/web/20241225114251/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



Next Article

Similar Reads

three90RightbarBannerImg