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

Check for Balanced Brackets in an expression (well-formedness)

Last Updated : 15 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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

Example: 

Input: exp = “[()]{}{[()()]()}” 
Output: Balanced
Explanation: all the brackets are well-formed

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

Check for Balanced Bracket expression using Stack:

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.

Illustration: 
Below is the illustration of the above approach.

Follow the steps mentioned below to implement the idea:

  • 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.

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 areBracketsBalanced(string expr)
{
    // Declare a stack to hold the previous brackets.
    stack<char> temp;
    for (int i = 0; i < expr.length(); i++) {
        if (temp.empty()) {
            
            // If the stack is empty 
            // just push the current bracket
            temp.push(expr[i]);
        }
        else if ((temp.top() == '(' && expr[i] == ')')
                 || (temp.top() == '{' && expr[i] == '}')
                 || (temp.top() == '[' && expr[i] == ']')) {
            
            // If we found any complete pair of bracket
            // then pop
            temp.pop();
        }
        else {
            temp.push(expr[i]);
        }
    }
    if (temp.empty()) {
        
        // If stack is empty return true
        return true;
    }
    return false;
}

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

    // Function call
    if (areBracketsBalanced(expr))
        cout << "Balanced";
    else
        cout << "Not Balanced";
    return 0;
}
C
#include <stdio.h>
#include <stdlib.h>
#define bool int

// Structure of a stack node
struct sNode {
    char data;
    struct sNode* next;
};

// Function to push an item to stack
void push(struct sNode** top_ref, int new_data);

// Function to pop an item from stack
int pop(struct sNode** top_ref);

// Returns 1 if character1 and character2 are matching left
// and right Brackets
bool isMatchingPair(char character1, char character2)
{
    if (character1 == '(' && character2 == ')')
        return 1;
    else if (character1 == '{' && character2 == '}')
        return 1;
    else if (character1 == '[' && character2 == ']')
        return 1;
    else
        return 0;
}

// Return 1 if expression has balanced Brackets
bool areBracketsBalanced(char exp[])
{
    int i = 0;

    // Declare an empty character stack
    struct sNode* stack = NULL;

    // Traverse the given expression to check matching
    // brackets
    while (exp[i]) {
        // If the exp[i] is a starting bracket then push
        // it
        if (exp[i] == '{' || exp[i] == '(' || exp[i] == '[')
            push(&stack, exp[i]);

        // If exp[i] is an ending bracket then pop from
        // stack and check if the popped bracket is a
        // matching pair*/
        if (exp[i] == '}' || exp[i] == ')'
            || exp[i] == ']') {

            // If we see an ending bracket without a pair
            // then return false
            if (stack == NULL)
                return 0;

            // Pop the top element from stack, if it is not
            // a pair bracket of character then there is a
            // mismatch.
            // his happens for expressions like {(})
            else if (!isMatchingPair(pop(&stack), exp[i]))
                return 0;
        }
        i++;
    }

    // If there is something left in expression then there
    // is a starting bracket without a closing
    // bracket
    if (stack == NULL)
        return 1; // balanced
    else
        return 0; // not balanced
}

// Driver code
int main()
{
    char exp[100] = "{()}[]";

    // Function call
    if (areBracketsBalanced(exp))
        printf("Balanced \n");
    else
        printf("Not Balanced \n");
    return 0;
}

// Function to push an item to stack
void push(struct sNode** top_ref, int new_data)
{
    // allocate node
    struct sNode* new_node
        = (struct sNode*)malloc(sizeof(struct sNode));

    if (new_node == NULL) {
        printf("Stack overflow n");
        getchar();
        exit(0);
    }

    // put in the data
    new_node->data = new_data;

    // link the old list of the new node
    new_node->next = (*top_ref);

    // move the head to point to the new node
    (*top_ref) = new_node;
}

// Function to pop an item from stack
int pop(struct sNode** top_ref)
{
    char res;
    struct sNode* top;

    // If stack is empty then error
    if (*top_ref == NULL) {
        printf("Stack overflow n");
        getchar();
        exit(0);
    }
    else {
        top = *top_ref;
        res = top->data;
        *top_ref = top->next;
        free(top);
        return res;
    }
}
Java
// Java program for checking
// balanced brackets
import java.util.*;

public class BalancedBrackets {

    // function to check if brackets are balanced
    static boolean areBracketsBalanced(String expr)
    {
        // Using ArrayDeque is faster than using Stack class
        Deque<Character> stack
            = new ArrayDeque<Character>();

        // Traversing the Expression
        for (int i = 0; i < expr.length(); i++) {
            char x = expr.charAt(i);

            if (x == '(' || x == '[' || x == '{') {
                // Push the element in the stack
                stack.push(x);
                continue;
            }

            // If current character is not opening
            // bracket, then it must be closing. So stack
            // cannot be empty at this point.
            if (stack.isEmpty())
                return false;
            char check;
            switch (x) {
            case ')':
                check = stack.pop();
                if (check == '{' || check == '[')
                    return false;
                break;

            case '}':
                check = stack.pop();
                if (check == '(' || check == '[')
                    return false;
                break;

            case ']':
                check = stack.pop();
                if (check == '(' || check == '{')
                    return false;
                break;
            }
        }

        // Check Empty Stack
        return (stack.isEmpty());
    }

    // Driver code
    public static void main(String[] args)
    {
        String expr = "([{}])";

        // Function call
        if (areBracketsBalanced(expr))
            System.out.println("Balanced ");
        else
            System.out.println("Not Balanced ");
    }
}
Python
# Python3 program to check for
# balanced brackets.

# function to check if
# brackets are balanced


def areBracketsBalanced(expr):
    stack = []

    # Traversing the Expression
    for char in expr:
        if char in ["(", "{", "["]:

            # Push the element in the stack
            stack.append(char)
        else:

            # IF current character is not opening
            # bracket, then it must be closing.
            # So stack cannot be empty at this point.
            if not stack:
                return False
            current_char = stack.pop()
            if current_char == '(':
                if char != ")":
                    return False
            if current_char == '{':
                if char != "}":
                    return False
            if current_char == '[':
                if char != "]":
                    return False

    # Check Empty Stack
    if stack:
        return False
    return True


# Driver Code
if __name__ == "__main__":
    expr = "{()}[]"

    # Function call
    if areBracketsBalanced(expr):
        print("Balanced")
    else:
        print("Not Balanced")

# This code is contributed by AnkitRai01 and improved
# by Raju Pitta
C#
// C# program for checking
// balanced Brackets
using System;
using System.Collections.Generic;

public class BalancedBrackets {
    public class stack {
        public int top = -1;
        public char[] items = new char[100];

        public void push(char x)
        {
            if (top == 99) {
                Console.WriteLine("Stack full");
            }
            else {
                items[++top] = x;
            }
        }

        char pop()
        {
            if (top == -1) {
                Console.WriteLine("Underflow error");
                return '\0';
            }
            else {
                char element = items[top];
                top--;
                return element;
            }
        }

        Boolean isEmpty()
        {
            return (top == -1) ? true : false;
        }
    }

    // Returns true if character1 and character2
    // are matching left and right brackets */
    static Boolean isMatchingPair(char character1,
                                  char character2)
    {
        if (character1 == '(' && character2 == ')')
            return true;
        else if (character1 == '{' && character2 == '}')
            return true;
        else if (character1 == '[' && character2 == ']')
            return true;
        else
            return false;
    }

    // Return true if expression has balanced
    // Brackets
    static Boolean areBracketsBalanced(char[] exp)
    {
        // Declare an empty character stack */
        Stack<char> st = new Stack<char>();

        // Traverse the given expression to
        //   check matching brackets
        for (int i = 0; i < exp.Length; i++) {
            // If the exp[i] is a starting
            // bracket then push it
            if (exp[i] == '{' || exp[i] == '('
                || exp[i] == '[')
                st.Push(exp[i]);

            //  If exp[i] is an ending bracket
            //  then pop from stack and check if the
            //   popped bracket is a matching pair
            if (exp[i] == '}' || exp[i] == ')'
                || exp[i] == ']') {

                // If we see an ending bracket without
                //   a pair then return false
                if (st.Count == 0) {
                    return false;
                }

                // Pop the top element from stack, if
                // it is not a pair brackets of
                // character then there is a mismatch. This
                // happens for expressions like {(})
                else if (!isMatchingPair(st.Pop(),
                                         exp[i])) {
                    return false;
                }
            }
        }

        // If there is something left in expression
        // then there is a starting bracket without
        // a closing bracket

        if (st.Count == 0)
            return true; // balanced
        else {
            // not balanced
            return false;
        }
    }

    // Driver code
    public static void Main(String[] args)
    {
        char[] exp = { '{', '(', ')', '}', '[', ']' };

        // Function call
        if (areBracketsBalanced(exp))
            Console.WriteLine("Balanced ");
        else
            Console.WriteLine("Not Balanced ");
    }
}

// This code is contributed by 29AjayKumar
Javascript
<script>

// Javascript program for checking
// balanced brackets

// Function to check if brackets are balanced
function areBracketsBalanced(expr)
{
    
    // Using ArrayDeque is faster
    // than using Stack class
    let stack = [];

    // Traversing the Expression
    for(let i = 0; i < expr.length; i++)
    {
        let x = expr[i];

        if (x == '(' || x == '[' || x == '{')
        {
            
            // Push the element in the stack
            stack.push(x);
            continue;
        }

        // If current character is not opening
        // bracket, then it must be closing. 
        // So stack cannot be empty at this point.
        if (stack.length == 0)
            return false;
            
        let check;
        switch (x){
        case ')':
            check = stack.pop();
            if (check == '{' || check == '[')
                return false;
            break;

        case '}':
            check = stack.pop();
            if (check == '(' || check == '[')
                return false;
            break;

        case ']':
            check = stack.pop();
            if (check == '(' || check == '{')
                return false;
            break;
        }
    }

    // Check Empty Stack
    return (stack.length == 0);
}

// Driver code
let expr = "([{}])";

// Function call
if (areBracketsBalanced(expr))
    document.write("Balanced ");
else
    document.write("Not Balanced ");

// This code is contributed by rag2127

</script>

Output
Balanced

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

Check for Balanced Bracket expression without using stack :

Following are the steps to be followed:

  • Initialize a variable i with -1.
  • Iterate through the string and 
    • If it is an open bracket then increment the counter by 1 and replace ith character of the string with the opening bracket.
    • Else if it is a closing bracket of the same corresponding opening bracket (opening bracket stored in exp[i]) then decrement i by 1.
  • At last, if we get i = -1, then the string is balanced and we will return true. Otherwise, the function will return false.

Below is the implementation of the above approach:

C++
#include <iostream>

using namespace std;

 bool areBracketsBalanced(string s) {
        int i=-1;
        for(auto& ch:s){
            if(ch=='(' || ch=='{' || ch=='[')
                s[++i]=ch;
            else{
                if(i>=0 && ((s[i]=='(' && ch==')') || (s[i]=='{' && ch=='}') || (s[i]=='[' && ch==']')))
                    i--;
                else
                    return false;
            }
        }
        return i==-1;
    }

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

    // Function call
    if (areBracketsBalanced(expr))
        cout << "Balanced";
    else
        cout << "Not Balanced";
    return 0;
}
Java
public class GFG {
    public static boolean areBracketsBalanced(String s)
    {
        int i = -1;
        char[] stack = new char[s.length()];
        for (char ch : s.toCharArray()) {
            if (ch == '(' || ch == '{' || ch == '[')
                stack[++i] = ch;
            else {
                if (i >= 0
                    && ((stack[i] == '(' && ch == ')')
                        || (stack[i] == '{' && ch == '}')
                        || (stack[i] == '[' && ch == ']')))
                    i--;
                else
                    return false;
            }
        }
        return i == -1;
    }

    public static void main(String[] args)
    {
        String expr = "{()}[]";

        // Function call
        if (areBracketsBalanced(expr))
            System.out.println("Balanced");
        else
            System.out.println("Not Balanced");
    }
}
Python
def are_brackets_balanced(s):
    stack = []
    for ch in s:
        if ch in ('(', '{', '['):
            stack.append(ch)
        else:
            if stack and ((stack[-1] == '(' and ch == ')') or
                          (stack[-1] == '{' and ch == '}') or
                          (stack[-1] == '[' and ch == ']')):
                stack.pop()
            else:
                return False
    return not stack

expr = "{()}[]"

# Function call
if are_brackets_balanced(expr):
    print("Balanced")
else:
    print("Not Balanced")
C#
// c# implementation

using System;

public class GFG {
    static bool areBracketsBalanced(string s) {
        int i = -1;
        char[] stack = new char[s.Length];
        foreach (char ch in s) {
            if (ch == '(' || ch == '{' || ch == '[')
                stack[++i] = ch;
            else {
                if (i >= 0 && ((stack[i] == '(' && ch == ')') || (stack[i] == '{' && ch == '}') || (stack[i] == '[' && ch == ']')))
                    i--;
                else
                    return false;
            }
        }
        return i == -1;
    }

    static void Main() {
        string expr = "{()}[]";

        // Function call
        if (areBracketsBalanced(expr))
            Console.WriteLine("Balanced");
        else
            Console.WriteLine("Not Balanced");
    }
}
// ksam24000
Javascript
function areBracketsBalanced(s) {
    let i = -1;
    let stack = [];
    for (let ch of s) {
        if (ch === '(' || ch === '{' || ch === '[') {
            stack.push(ch);
            i++;
        } else {
            if (i >= 0 && ((stack[i] === '(' && ch === ')') || (stack[i] === '{' && ch === '}') || (stack[i] === '[' && ch === ']'))) {
                stack.pop();
                i--;
            } else {
                return false;
            }
        }
    }
    return i === -1;
}

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

// Function call
if (areBracketsBalanced(expr))
    console.log("Balanced");
else
    console.log("Not Balanced");

Output
Balanced

Time Complexity: O(N), Iteration over the string of size N one time.
Auxiliary Space: O(N), to store char array



Previous Article
Next Article

Similar Reads

Javascript Program To Check For Balanced Brackets In An Expression (Well-Formedness) Using Stack
Given an expression string exp, write a program to examine whether the pairs and the orders of "{", "}", "(", ")", "[", "]" are correct in exp. Example:  Input: exp = "[()]{}{[()()]()}" Output: Balanced Input: exp = "[(])" Output: Not Balanced  Recommended: Please solve it on “PRACTICE ” first, before moving on to the solution.   Algorithm:  Declar
2 min read
Print the balanced bracket expression using given brackets
Given four integers a, b, c and d which signifies the number of four types of brackets. "((""()"")(""))" The task is to print any balanced bracket expression using all the given brackets. If we cannot form a balanced bracket expression then print -1. In case of multiple answers, print any one. Examples: Input: a = 3, b = 1, c = 4, d = 3 Output: (((
6 min read
Check if it is possible to obtain a Balanced Parenthesis by shifting brackets to either end at most K times
Given a string S of size N consisting of only '(' and ')' only and a positive integer K, the task is to check if the given string can be made a valid parenthesis sequence by moving any characters of the string S to either end of the string at most K number of times. Examples: Input: S = ")(", K = 1Output: YesExplanation: Move S[0] to the end of the
8 min read
Balanced expressions such that given positions have opening brackets | Set 2
Given an integer n and an array of positions ‘position[]’ (1 &lt;= length(position[]) &lt;= 2n), find the number of ways of proper bracket expressions that can be formed of length 2n such that given positions have the opening bracket. Note: position[] array is given in the form of (1-based indexing) [0, 1, 1, 0]. Here 1 denotes the positions at whi
15+ min read
Print all Balanced Brackets Strings that can be formed by replacing wild card '?'
Given string str containing characters '?', '(' and ')', the task is to replace the '?' character with '(' or ')' and print all the strings containing balanced brackets Example: Input: str = "????"Output:()()(()) Input: str = "(()?"Output: (()) Approach: The given problem can be solved using recursion and backtracking. The idea is to substitute eve
10 min read
Balanced expressions such that given positions have opening brackets
Given an integer n and an array of positions 'position[]' (1 &lt;= position[i] &lt;= 2n), find the number of ways of proper bracket expressions that can be formed of length 2n such that given positions have opening bracket.Examples : Input : n = 3, position[] = [2}Output : 3 Explanation : The proper bracket sequences of length 6 and opening bracket
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
Comparison between Height Balanced Tree and Weight Balanced Tree
What is Height Balanced Tree? Self-Balancing binary search trees are the height-balanced binary tree is one for which at every node, the absolute value of the difference in heights of the left and right subtree is no larger than one. An empty tree is height-balanced. A non-empty binary tree T is balanced if: The left subtree of T is balanced.The ri
4 min read
Balanced expression with replacement
Given a string that contains only the following =&gt; ‘{‘, ‘}’, ‘(‘, ‘)’, ‘[’, ‘]’. At some places there is ‘X’ in place of any bracket. Determine whether by replacing all ‘X’s with appropriate bracket, is it possible to make a valid bracket sequence. Prerequisite: Balanced Parenthesis Expression Examples: Input : S = "{(X[X])}" Output : Balanced T
13 min read
Minimum number of bracket reversals needed to make an expression balanced
Given an expression with only '}' and '{'. The expression may not be balanced. Find minimum number of bracket reversals to make the expression balanced.Examples: Input: exp = "}{"Output: 2We need to change '}' to '{' and '{' to'}' so that the expression becomes balanced, the balanced expression is '{}'Input: exp = "{{{"Output: Can't be made balance
15+ min read
Minimum number of bracket reversals needed to make an expression balanced | Set - 2
Given an expression with only '}' and '{'. The expression may not be balanced. The task is to find minimum number of bracket reversals to make the expression balanced.Examples: Input : exp = "}{"Output : 2We need to change '}' to '{' and '{' to'}' so that the expression becomes balanced, the balanced expression is '{}'Input : exp = "}{{}}{{{"Output
11 min read
Check if two expressions with brackets are same
Given two expressions in the form of strings. The task is to compare them and check if they are similar. Expressions consist of lowercase alphabets, '+', '-' and '( )'. Examples: Input : exp1 = "-(a+b+c)" exp2 = "-a-b-c" Output : Yes Input : exp1 = "-(c+b+a)" exp2 = "-c-b-a" Output : Yes Input : exp1 = "a-b-(c-d)" exp2 = "a-b-c-d" Output : No It ma
11 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
Minimum flips required to form given binary string where every flip changes all bits to its right as well
Given a string S, the task is to find minimum flips required to convert an initial binary string consisting of only zeroes to S where every flip of a character flips all succeeding characters as well. Examples: Input: S = "01011" Output: 3 Explanation: Initial String - "00000" Flip the 2nd bit - "01111" Flip the 3rd bit - "01000" Flip the 4th bit -
4 min read
Count array elements exceeding all previous elements as well as the next array element
Given an array arr[], the task is to find the count of array elements satisfying the following conditions: The array elements should be strictly greater than all the previously occurring array elements.Either it is the last array element or the integer should be strictly larger than the next array element. Note: The first integer of the array can a
6 min read
Number of points lying inside a rectangle as well as a triangle
Given two 2D arrays rectangle[][] and triangle[][], representing the coordinates of vertices of a rectangle and a triangle respectively, and another array points[][] consisting of N coordinates, the task is to count the number of points that lies inside both the rectangle and the triangle. Examples: Input: rectangle[][] = {{1, 1}, {6, 1}, {6, 6}, {
15 min read
Minimum distance to fetch water from well in a village
Given a 2-D matrix of characters of size n*m, where H - Represents a house, W - Represents a well, O - Represents an open ground, and N - Prohibited area(Not allowed to enter in this area). Every house in the village needs to take the water from the well, as the family members are so busy with their work, so every family wants to take the water fro
13 min read
Find Largest and smallest number in an Array containing small as well as large numbers
Given an array arr[] of N small and/or large numbers, the task is to find the largest and smallest number in this array. Examples: Input: N = 4, arr[] = {5677856, 657856745356587687698768, 67564, 45675645356576578564435647647}Output: Smallest: 67564Largest: 45675645356576578564435647647 Input: N = 5, arr[] = {56, 64, 765, 323, 4764}Output: Smallest
10 min read
Number of closing brackets needed to complete a regular bracket sequence
Given an incomplete bracket sequence S. The task is to find the number of closing brackets ')' needed to make it a regular bracket sequence and print the complete bracket sequence. You are allowed to add the brackets only at the end of the given bracket sequence. If it is not possible to complete the bracket sequence, print "IMPOSSIBLE". Let us def
7 min read
Binary tree to string with brackets
Construct a string consists of parenthesis and integers from a binary tree with the preorder traversing way. The null node needs to be represented by empty parenthesis pair "()". Omit all the empty parenthesis pairs that don't affect the one-to-one mapping relationship between the string and the original binary tree. Examples: Input : Preorder: [1,
8 min read
Balance a string after removing extra brackets
Given a string of characters with opening and closing brackets. The task is to remove extra brackets from string and balance it. Examples: Input: str = "gau)ra)v(ku(mar(rajput))" Output: gaurav(ku(mar(rajput))) Input: str = "1+5)+5+)6+(5+9)*9" Output: 1+5+5+6+(5+9)*9 Approach: Start traversing from left to right.Check if the element at current inde
6 min read
Minimum swaps to balance the given brackets at any index
Given a balanced string of even length consisting of equal number of opening brackets ‘[‘ and closing brackets ‘]’ , Calculate the minimum number of swaps to make string balanced. An unbalanced string can be made balanced by swapping any two brackets. A string is called balanced if it can be represented in the form of "[S1]" where S1 is a balanced
5 min read
Printing brackets in Matrix Chain Multiplication Problem
Prerequisite : Dynamic Programming | Set 8 (Matrix Chain Multiplication) Given a sequence of matrices, find the most efficient way to multiply these matrices together. The problem is not actually to perform the multiplications, but merely to decide in which order to perform the multiplications. We have many options to multiply a chain of matrices b
15+ min read
Find an equal point in a string of brackets
Given a string of brackets, the task is to find an index k which decides the number of opening brackets is equal to the number of closing brackets. The string must be consists of only opening and closing brackets i.e. '(' and ')'. An equal point is an index such that the number of opening brackets before it is equal to the number of closing bracket
14 min read
Remove brackets from an algebraic string containing + and - operators
Simplify a given algebraic string of characters, '+', '-' operators and parentheses. Output the simplified string without parentheses. Examples: Input : "(a-(b+c)+d)" Output : "a-b-c+d" Input : "a-(b-c-(d+e))-f" Output : "a-b+c+d+e-f" The idea is to check operators just before starting of bracket, i.e., before character '('. If operator is -, we ne
8 min read
Check if a given Binary Tree is height balanced like a Red-Black Tree
In a Red-Black Tree, the maximum height of a node is at most twice the minimum height (The four Red-Black tree properties make sure this is always followed). Given a Binary Search Tree, we need to check for following property. For every node, length of the longest leaf to node path has not more than twice the nodes on shortest path from node to lea
9 min read
Check if a given string can be converted to a Balanced Bracket Sequence
Given a string S of size N consisting of '(', ')', and '$', the task is to check whether the given string can be converted into a balanced bracket sequence by replacing every occurrence of $ with either ) or (. A balanced bracket sequence is a sequence where every opening bracket "(" has a corresponding closing bracket ")". Examples: Input: S = "()
12 min read
Check if concatenation of two strings is balanced or not
Given two bracket sequences S1 and S2 consisting of '(' and ')'. The task is to check if the string obtained by concatenating both the sequences is balanced or not. Concatenation can be done by s1+s2 or s2+s1. Examples: Input: s1 = ")()(())))", s2 = "(()(()(" Output: Balanced s2 + s1 = "(()(()()()(())))", which is a balanced parenthesis sequence. I
15 min read
Check if the bracket sequence can be balanced with at most one change in the position of a bracket
Given an unbalanced bracket sequence as a string str, the task is to find whether the given string can be balanced by moving at most one bracket from its original place in the sequence to any other position.Examples: Input: str = ")(()" Output: Yes As by moving s[0] to the end will make it valid. "(())"Input: str = "()))(()" Output: No Approach: Co
6 min read
Check if the bracket sequence can be balanced with at most one change in the position of a bracket | Set 2
Given a bracket sequence as a string str, the task is to find whether the given string can be balanced by moving at most one bracket from its original place in the sequence to any other position.Examples: Input: str = ")(()" Output: Yes As by moving s[0] to the end will make it valid. "(())"Input: str = "()))(()" Output: No Approach: The problem ca
5 min read