Approach : Using a Stack

This is the most common and efficient approach to check for balanced brackets.

Algorithm Steps:

  • Initialize an empty stack.
  • Traverse the string character by character.
  • If the character is an opening bracket (‘(‘, ‘{‘, ‘[‘) push it onto the stack.
  • If the character is a closing bracket (‘)’, ‘}’, ‘]’) :
    1. Check if the stack is empty. If it is, return No because there is no corresponding opening bracket.
    2. Otherwise, pop the top element from the stack and check if it matches the corresponding opening bracket. If it doesn’t match, return No.
  • After traversing the string, check if the stack is empty. If it is empty, return Yes indicating the brackets are balanced. If it is not empty, return No.

Below is the implementation of the above approach: 

C++
#include <iostream>
#include <stack>
#include <unordered_map>

using namespace std;

string is_balanced(const string& s)
{
    // Initialize an empty stack to keep track of opening
    // brackets
    stack<char> stack;

    // A map to associate closing brackets with their
    // corresponding opening brackets
    unordered_map<char, char> bracket_map
        = { { ')', '(' }, { '}', '{' }, { ']', '[' } };

    // Traverse each character in the string
    for (char chr : s) {
        if (bracket_map.find(chr) == bracket_map.end()) {
            // If the character is an opening bracket, push
            // it onto the stack
            stack.push(chr);
        }
        else {
            // If the character is a closing bracket
            if (stack.empty()
                || stack.top() != bracket_map[chr]) {
                // Check if the stack is empty or the top of
                // the stack does not match the
                // corresponding opening bracket
                return "No"; // The brackets are not
                             // balanced
            }
            stack.pop();
        }
    }

    // If the stack is empty, all opening brackets had a
    // matching closing bracket in the correct order If the
    // stack is not empty, there are unmatched opening
    // brackets
    return stack.empty() ? "Yes" : "No";
}

// Example usage
int main()
{
    cout << is_balanced("(()[]") << endl; // Output: No
    cout << is_balanced("))(({}{") << endl; // Output: No

    return 0;
}
Python
def is_balanced(s):
    # Initialize an empty stack to keep track of opening brackets
    stack = []

    # A dictionary to map closing brackets to their corresponding opening brackets
    bracket_map = {')': '(', '}': '{', ']': '['}

    # Traverse each character in the string
    for char in s:
        if char in bracket_map.values():
            # If the character is an opening bracket, push it onto the stack
            stack.append(char)
        elif char in bracket_map:
            # If the character is a closing bracket
            if not stack or stack.pop() != bracket_map[char]:
                # Check if the stack is empty or the top of the stack does 
                # not match the corresponding opening bracket
                return "No"  # The brackets are not balanced

    # If the stack is empty, all opening brackets had a matching closing 
    # bracket in the correct order
    # If the stack is not empty, there are unmatched opening brackets
    return "Yes" if not stack else "No"


print(is_balanced("(()[]"))
print(is_balanced("))(({}{"))
JavaScript
function is_balanced(s) {
    // Initialize an empty stack to keep track of opening brackets
    const stack = [];

    // A map to associate closing brackets with their corresponding opening brackets
    const bracket_map = {
        ')': '(',
        '}': '{',
        ']': '['
    };

    // Traverse each character in the string
    for (const chr of s) {
        if (!(chr in bracket_map)) {
            // If the character is an opening bracket, push it onto the stack
            stack.push(chr);
        } else {
            // If the character is a closing bracket
            if (stack.length === 0 || stack[stack.length - 1] !== bracket_map[chr]) {
                // Check if the stack is empty or the top of the stack does not match
                // the corresponding opening bracket
                return "No"; // The brackets are not balanced
            }
            stack.pop();
        }
    }

    // If the stack is empty, all opening brackets had a matching closing bracket in 
    // the correct order
    // If the stack is not empty, there are unmatched opening brackets
    return stack.length === 0 ? "Yes" : "No";
}

// Example usage
console.log(is_balanced("(()[]")); // Output: No
console.log(is_balanced("))(({}{")); // Output: No
// This code is contributed by Yash Agarwal

Output
No
No
  • Time complexity: O(n)
  • Auxiliary Space: O(n)




Check for balanced parentheses in an expression | O(1) space | O(N^2) time complexity

Given a string str containing characters ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[‘ and ‘]’, the task is to determine if brackets are balanced or not. Brackets are balanced if:

  1. Open brackets must be closed by the same type of brackets.
  2. Open brackets must be closed in the correct order.

Examples:

Input: str = “(())[]” Output: Yes Input: str = “))(({}{” Output: No

Approach:

  • Keep two variables i and j to keep track of two brackets to be compared.
  • Maintain a count whose value increments on encountering opening bracket and decrements on encountering a closing bracket.
  • Set j = i, i = i + 1 and counter++ when opening brackets are encountered.
  • When Closing brackets are encountered decrement count and compare brackets at i and j,
    • If brackets at i and j are a match, then substitute ‘#’ in string at ith and jth position. Increment i and decrement j until non ‘#’ value is encountered or j ? 0.
    • If brackets at i and j are not a match then return false.
  • If count != 0 then return false.

Below is the implementation of the above approach: 

C++
// C++ implementation of the approach 
#include <iostream> 
using namespace std; 

// This helper function is called whenever 
// closing bracket is encountered. 
// Hence count is decremented 
// j and i points to opening and closing 
// brackets to be matched respectively 
// If brackets at i and j is a match 
// replace them with "#" character and decrement j 
// to point next opening bracket to * be matched 
// Similarly, increment i to point to next closing 
// bracket to be matched 
// If j is out of bound or brackets did not match return 0 
bool helperFunc(int& count, string& s, int& i, int& j, char tocom) 
{ 
    count--; 
    if (j > -1 && s[j] == tocom) { 
        s[i] = '#'; 
        s[j] = '#'; 
        while (j >= 0 && s[j] == '#') 
            j--; 
        i++; 
        return 1; 
    } 
    else
        return 0; 
} 

// Function that returns true if s is a 
// valid balanced bracket string 
bool isValid(string s) 
{ 

    // Empty string is considered balanced 
    if (s.length() == 0) 
        return true; 

    else { 
        int i = 0; 

        // Increments for opening bracket and 
        // decrements for closing bracket 
        int count = 0; 
        int j = -1; 
        bool result; 
        while (i < s.length()) { 
            switch (s[i]) { 
            case '}': 
                result = helperFunc(count, s, i, j, '{'); 
                if (result == 0) { 
                    return false; 
                } 
                break; 

            case ')': 
                result = helperFunc(count, s, i, j, '('); 
                if (result == 0) { 
                    return false; 
                } 
                break; 

            case ']': 
                result = helperFunc(count, s, i, j, '['); 
                if (result == 0) { 
                    return false; 
                } 
                break; 

            default: 
                j = i; 
                i++; 
                count++; 
            } 
        } 

        // count != 0 indicates unbalanced parentheses 
        // this check is required to handle cases where 
        // count of opening brackets > closing brackets 
        if (count != 0) 
            return false; 

        return true; 
    } 
} 

// Driver code 
int main() 
{ 
    string str = "[[]][]()"; 

    if (isValid(str)) 
        cout << "Yes"; 
    else
        cout << "No"; 

    return 0; 
} 
Java
// Java implementation of the approach 
import java.util.*; 

class GFG 
{ 

    static String s = "[[]][]()"; 
    static int count = 0; 
    static int i = 0; 
    static int j = -1; 

// This helper function is called whenever 
// closing bracket is encountered. 
// Hence count is decremented 
// j and i points to opening and closing 
// brackets to be matched respectively 
// If brackets at i and j is a match 
// replace them with "#" character and decrement j 
// to point next opening bracket to * be matched 
// Similarly, increment i to point to next closing 
// bracket to be matched 
// If j is out of bound or brackets did not match return 0 
static int helperFunc(char tocom) 
{ 
    count--; 
    char temp = s.charAt(j); 
    if (j > -1 && temp == tocom) 
    { 
        s = s.replace(s.charAt(i),'#'); 
        s = s.replace(s.charAt(j),'#'); 
        temp = s.charAt(j); 
        while (j >= 0 && temp == '#') 
            j--; 
        i++; 
        return 1; 
    } 
    else
        return 0; 
} 

// Function that returns true if s is a 
// valid balanced bracket string 
static boolean isValid() 
{ 

    // Empty string is considered balanced 
    if (s.length() == 0) 
        return true; 

    else { 
        int result; 
        while (i < s.length()) 
        { 
            char temp = s.charAt(i); 
            if(temp=='}') 
            { 
                result = helperFunc('{'); 
                if (result == 0) 
                { 
                    return false; 
                } 
            } 
            else if(temp == ')') 
            { 
                result = helperFunc('('); 
                if (result == 0) 
                { 
                    return false; 
                } 
            } 

            else if(temp == ']') 
            { 
                result = helperFunc('['); 
                if (result == 0) 
                { 
                    return false; 
                } 
            } 
                
            else
            { 
                j = i; 
                i++; 
                count++; 
            } 
        } 

        // count != 0 indicates unbalanced parentheses 
        // this check is required to handle cases where 
        // count of opening brackets > closing brackets 
        if (count != 0) 
            return false; 

        return true; 
    } 
} 

// Driver code 
public static void main(String args[]) 
{ 
    if (isValid()) 
    System.out.println("No"); 
    else
    System.out.println("Yes"); 
} 

} 

// This code is contributed by Surendra_Gangwar 
Python
# Python3 implementation of the approach 

# These are defined as global because they 
# are passed by reference 
count = 0
i = 0
j = -1

# This helper function is called whenever 
# closing bracket is encountered. 
# Hence count is decremented 
# j and i points to opening and closing 
# brackets to be matched respectively 
# If brackets at i and j is a match 
# replace them with "#" character and decrement j 
# to point next opening bracket to * be matched 
# Similarly, increment i to point to next closing 
# bracket to be matched 
# If j is out of bound or brackets 
# did not match return 0 
def helperFunc(s, tocom): 
    global i, j, count 
    count -= 1
    if j > -1 and s[j] == tocom: 
        s[i] = '#'
        s[j] = '#'
        while j >= 0 and s[j] == '#': 
            j -= 1
        i += 1
        return 1
    else: 
        return 0

# Function that returns true if s is a 
# valid balanced bracket string 
def isValid(s): 
    global i, j, count 

    # Empty string is considered balanced 
    if len(s) == 0: 
        return True
    else: 

        # Increments for opening bracket and 
        # decrements for closing bracket 
        result = False
        while i < len(s): 
            if s[i] == '}': 
                result = helperFunc(s, '{') 
                if result == 0: 
                    return False
            elif s[i] == ')': 
                result = helperFunc(s, '(') 
                if result == 0: 
                    return False
            elif s[i] == ']': 
                result = helperFunc(s, '[') 
                if result == 0: 
                    return False
            else: 
                j = i 
                i += 1
                count += 1

        # count != 0 indicates unbalanced parentheses 
        # this check is required to handle cases where 
        # count of opening brackets > closing brackets 
        if count != 0: 
            return False
        return True

# Driver Code 
if __name__ == "__main__": 
    string = "[[]][]()"
    string = list(string) 

    print("Yes") if isValid(string) else print("No") 

# This code is contributed by 
# sanjeev2552 
C#
// C# implementation of the approach
using System;

class GFG{

static string s = "[[]][]()";
static int count = 0;
static int i = 0;
static int j = -1;

// This helper function is called whenever
// closing bracket is encountered. Hence 
// count is decremented j and i points to
// opening and closing brackets to be matched 
// respectively. If brackets at i and j is a match
// replace them with "#" character and decrement j
// to point next opening bracket to * be matched
// Similarly, increment i to point to next closing
// bracket to be matched. If j is out of bound or
// brackets did not match return 0
static int helperFunc(char tocom)
{
    count--;
    char temp = s[j];
    
    if (j > -1 && temp == tocom) 
    {
        s = s.Replace(s[i],'#');
        s = s.Replace(s[j],'#');
        
        temp = s[j];
        while (j >= 0 && temp == '#')
            j--;
            
        i++;
        return 1;
    }
    else
        return 0;
}

// Function that returns true if s is a
// valid balanced bracket string
static bool isValid()
{

    // Empty string is considered balanced
    if (s.Length == 0)
        return true;

    else 
    {
        int result;
         while (i < s.Length) 
        { 
            char temp = s[i]; 
            if(temp == '}') 
            { 
                result = helperFunc('{'); 
                if (result == 0) 
                { 
                    return false; 
                } 
            } 
            
            else if(temp == ')') 
            { 
                result = helperFunc('('); 
                if (result == 0) 
                { 
                    return false; 
                } 
            } 
  
            else if(temp == ']') 
            { 
                result = helperFunc('['); 
                if (result == 0)  
                { 
                    return false; 
                } 
            } 
                  
            else
            { 
                j = i; 
                i++; 
                count++; 
            } 
        } 
        
        // count != 0 indicates unbalanced 
        // parentheses this check is required 
        // to handle cases where count of opening
        // brackets > closing brackets 
        if (count != 0)
            return false;

        return true;
    }
}

// Driver code
public static void Main(string []args)
{
    if (isValid())
    {
        Console.Write("No");
    }
    else
    {
        Console.Write("Yes");
    }
}
}

// This code is contributed by rutvik_56
Javascript
// JavaScript implementation of the approach 

// Increments for opening bracket and 
// decrements for closing bracket 
var i = 0; 
var count = 0; 
var j = -1; 
var s;

// This helper function is called whenever 
// closing bracket is encountered. 
// Hence count is decremented 
// j and i points to opening and closing 
// brackets to be matched respectively 
// If brackets at i and j is a match 
// replace them with "#" character and decrement j 
// to point next opening bracket to * be matched 
// Similarly, increment i to point to next closing 
// bracket to be matched 
// If j is out of bound or brackets did not match return 0 
function helperFunc(tocom) 
{ 
    count--; 
    if (j > -1 && s[j] == tocom) { 
        s[i] = '#'; 
        s[j] = '#'; 
        while (j >= 0 && s[j] == '#') 
            j--; 
        i++; 
        return 1; 
    } 
    else
        return 0; 
} 

// Function that returns true if s is a 
// valid balanced bracket string 
function isValid(str) 
{ 
    s = str.split("")
    
    // Empty string is considered balanced 
    if (s.length == 0) 
        return true; 

    else { 
        let result; 
        while (i < s.length) { 
            switch (s[i]) { 
            case '}': 
                result = helperFunc('{'); 
                if (result == 0) { 
                    return false; 
                } 
                break; 

            case ')': 
                result = helperFunc('('); 
                if (result == 0) { 
                    return false; 
                } 
                break; 

            case ']': 
                result = helperFunc('['); 
                if (result == 0) { 
                    return false; 
                } 
                break; 

            default: 
                j = i; 
                i++; 
                count++; 
            } 
        } 

        // count != 0 indicates unbalanced parentheses 
        // this check is required to handle cases where 
        // count of opening brackets > closing brackets 
        if (count != 0) 
            return false; 

        return true; 
    } 
} 

// Driver code 
let str = "[[]][]()"; 

if (isValid(str)) 
    console.log("Yes"); 
else
    console.log("No"); 

// This code is contributed by phasing17

Output
Yes

Time complexity: O(N^2) where N is length of input expression string

Auxiliary Space: O(1)

Similar Reads

Approach : Using a Stack

This is the most common and efficient approach to check for balanced brackets....