The Wayback Machine - https://web.archive.org/web/20240910025710/https://www.geeksforgeeks.org/print-all-combinations-of-balanced-parentheses/
Open In App

Print all combinations of balanced parentheses

Last Updated : 13 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Solve Problem
Medium
59.23%
37.5K

Given a number n, the task is to generate all possible n pairs of balanced parentheses.

Examples: 

Input: n=1
Output: {}
Explanation: This the only sequence of balanced parenthesis formed using 1 pair of balanced parenthesis.

Input : n=2
Output: {}{}
{{}}
Explanation: This the only two sequences of balanced parenthesis formed using 2 pair of balanced parenthesis.

Approach 1:

To form all the sequences of balanced bracket subsequences with n pairs. So there are n opening brackets and n closing brackets. So the subsequence will be of length 2*n.

There is a simple idea, the i’th character can be ‘{‘ if and only if the count of ‘{‘ till i’th is less than n and i’th character can be ‘}’ if and only if the count of ‘{‘ is greater than the count of ‘}’ till index i. If these two cases are followed then the resulting subsequence will always be balanced. So form the recursive function using the above two cases.

Algorithm:  

  • Create a recursive function that accepts a string (s), count of opening brackets (o) and count of closing brackets (c) and the value of n.
  • If the value of opening bracket and closing bracket is equal to n then print the string and return.
  • If the count of opening bracket is greater than count of closing bracket then call the function recursively with the following parameters String s + “}”, count of opening bracket o, count of closing bracket c + 1, and n.
  • If the count of opening bracket is less than n then call the function recursively with the following parameters String s + “{“, count of opening bracket o + 1, count of closing bracket c, and n.

 Below is the implementation of above approach:

C++
#include <iostream>

#define MAX_SIZE 100

void _printParenthesis(int pos, int n, int open, int close);

// Wrapper over _printParenthesis()
void printParenthesis(int n)
{
    if (n > 0)
        _printParenthesis(0, n, 0, 0);
    return;
}

void _printParenthesis(int pos, int n, int open, int close)
{
    static char str[MAX_SIZE];

    if (close == n) {
        std::cout << str << std::endl;
        return;
    }
    else {
        if (open > close) {
            str[pos] = '}';
            _printParenthesis(pos + 1, n, open, close + 1);
        }

        if (open < n) {
            str[pos] = '{';
            _printParenthesis(pos + 1, n, open + 1, close);
        }
    }
}

// Driver program to test above functions
int main()
{
    int n = 3;
    printParenthesis(n);
    return 0;
}
C
// C program to Print all combinations
// of balanced parentheses
#include <stdio.h>
#define MAX_SIZE 100

void _printParenthesis(int pos, int n, int open, int close);

// Wrapper over _printParenthesis()
void printParenthesis(int n)
{
    if (n > 0)
        _printParenthesis(0, n, 0, 0);
    return;
}

void _printParenthesis(int pos, int n, int open, int close)
{
    static char str[MAX_SIZE];

    if (close == n) {
        printf("%s \n", str);
        return;
    }
    else {
        if (open > close) {
            str[pos] = '}';
            _printParenthesis(pos + 1, n, open, close + 1);
        }

        if (open < n) {
            str[pos] = '{';
            _printParenthesis(pos + 1, n, open + 1, close);
        }
    }
}

// Driver program to test above functions
int main()
{
    int n = 3;
    printParenthesis(n);
    getchar();
    return 0;
}
Java
// Java program to print all
// combinations of balanced parentheses
import java.io.*;

class GFG {
    // Function that print all combinations of
    // balanced parentheses
    // open store the count of opening parenthesis
    // close store the count of closing parenthesis
    static void _printParenthesis(char str[], int pos,
                                  int n, int open,
                                  int close)
    {
        if (close == n) {
            // print the possible combinations
            for (int i = 0; i < str.length; i++)
                System.out.print(str[i]);
            System.out.println();
            return;
        }
        else {
            if (open > close) {
                str[pos] = '}';
                _printParenthesis(str, pos + 1, n, open,
                                  close + 1);
            }
            if (open < n) {
                str[pos] = '{';
                _printParenthesis(str, pos + 1, n, open + 1,
                                  close);
            }
        }
    }

    // Wrapper over _printParenthesis()
    static void printParenthesis(char str[], int n)
    {
        if (n > 0)
            _printParenthesis(str, 0, n, 0, 0);
        return;
    }

    // driver program
    public static void main(String[] args)
    {
        int n = 3;
        char[] str = new char[2 * n];
        printParenthesis(str, n);
    }
}

// Contributed by Pramod Kumar
Python
# Python3 program to
# Print all combinations
# of balanced parentheses

# Wrapper over _printParenthesis()


def printParenthesis(str, n):
    if(n > 0):
        _printParenthesis(str, 0,
                          n, 0, 0)
    return


def _printParenthesis(str, pos, n,
                      open, close):

    if(close == n):
        for i in str:
            print(i, end="")
        print()
        return
    else:
        if(open > close):
            str[pos] = '}'
            _printParenthesis(str, pos + 1, n,
                              open, close + 1)
        if(open < n):
            str[pos] = '{'
            _printParenthesis(str, pos + 1, n,
                              open + 1, close)


# Driver Code
n = 3
str = [""] * 2 * n
printParenthesis(str, n)

# This Code is contributed
# by mits.
C#
// C# program to print all
// combinations of balanced parentheses
using System;

class GFG {
    // Function that print all combinations of
    // balanced parentheses
    // open store the count of opening parenthesis
    // close store the count of closing parenthesis
    static void _printParenthesis(char[] str, int pos,
                                  int n, int open,
                                  int close)
    {
        if (close == n) {
            // print the possible combinations
            for (int i = 0; i < str.Length; i++)
                Console.Write(str[i]);

            Console.WriteLine();
            return;
        }
        else {
            if (open > close) {
                str[pos] = '}';
                _printParenthesis(str, pos + 1, n, open,
                                  close + 1);
            }
            if (open < n) {
                str[pos] = '{';
                _printParenthesis(str, pos + 1, n, open + 1,
                                  close);
            }
        }
    }

    // Wrapper over _printParenthesis()
    static void printParenthesis(char[] str, int n)
    {
        if (n > 0)
            _printParenthesis(str, 0, n, 0, 0);
        return;
    }

    // driver program
    public static void Main()
    {
        int n = 3;
        char[] str = new char[2 * n];

        printParenthesis(str, n);
    }
}

// This code is contributed by Sam007
JavaScript
<script>
// javascript program to print all 
// combinations of balanced parentheses

    // Function that print all combinations of
    // balanced parentheses
    // open store the count of opening parenthesis
    // close store the count of closing parenthesis
    function _printParenthesis( str , pos , n , open , close) 
    {
        if (close == n)
        {
        
            // print the possible combinations
            for (let i = 0; i < str.length; i++)
                document.write(str[i]);
            document.write("<br/>");
            return;
        } 
        else
        {
            if (open > close)
            {
                str[pos] = '}';
                _printParenthesis(str, pos + 1, n, open, close + 1);
            }
            if (open < n) 
            {
                str[pos] = '{';
                _printParenthesis(str, pos + 1, n, open + 1, close);
            }
        }
    }

    // Wrapper over _printParenthesis()
    function printParenthesis( str , n)
    {
        if (n > 0)
            _printParenthesis(str, 0, n, 0, 0);
        return;
    }

    // Driver program
    var n = 3;
    var str = new Array(2 * n);
    printParenthesis(str, n);

// This code is contributed by shikhasingrajput 
</script>
PHP
<?php
// PHP program to Print 
// all combinations of 
// balanced parentheses
$MAX_SIZE = 100;

// Wrapper over 
// _printParenthesis()
function printParenthesis($str, $n)
{
    if($n > 0)
        _printParenthesis($str, 0, 
                          $n, 0, 0);
    return;
} 

// Function that print 
// all combinations of 
    // balanced parentheses
    // open store the count of
    //  opening parenthesis
    // close store the count of 
    //  closing parenthesis
function _printParenthesis($str, $pos, $n, 
                           $open, $close)
{
    if($close == $n) 
    {
        for ($i = 0; 
             $i < strlen($str); $i++)
        echo $str[$i];
        echo "\n";
        return;
    }
    else
    {
        if($open > $close) 
        {
            $str[$pos] = '}';
            _printParenthesis($str, $pos + 1, $n,
                              $open, $close + 1);
        }
        
        if($open < $n)
        {
        $str[$pos] = '{';
        _printParenthesis($str, $pos + 1, $n, 
                          $open + 1, $close);
        }
    }
}

// Driver Code
$n = 3;
$str="     ";
printParenthesis($str, $n);

// This Code is contributed by mits.
?>

Output
{}{}{}
{}{{}}
{{}}{}
{{}{}}
{{{}}}

Time complexity: O(2^n), as there are 2^n possible combinations of ‘(‘ and ‘)’ parentheses.
Auxiliary space: O(n), as n characters are stored in the str array.

Print all combinations of balanced parentheses using DFS

The idea is to use recursive Depth-First Search (DFS) approach that explores different combinations while ensuring the parentheses remain balanced. The program starts with an empty string and builds valid combinations by adding open and close parentheses, finally printing all the valid combinations found.

  • Create two variables left and right representing the number of remaining open parentheses and number of remaining close parentheses.
  • During each recursive call, two possibilities are explored:
    • Adding an open parenthesis ‘{‘ to the current combination and decrementing left.
    • Adding a close parenthesis ‘}‘ to the current combination and decrementing right.
  • If at any point, the number of open parentheses becomes greater than the number of close parentheses or either left or right becomes negative, the combination is invalid, and that branch of the recursion is terminated.
  • When both left and right are zero, it will indicate a valid combination has been formed.

 Below is the implementation of above approach:

C++
// c++ program to print all the combinations of balanced
// parenthesis.
#include <bits/stdc++.h>
using namespace std;

void generateParenthesis(int left, int right, string& s,
                         vector<string>& answer)
{
    // terminate
    if (left == 0 && right == 0) {
        answer.push_back(s);
    }

    if (left > right || left < 0 || right < 0) {
        // wrong
        return;
    }

    s.push_back('{');
    generateParenthesis(left - 1, right, s, answer);
    s.pop_back();

    s.push_back('}');
    generateParenthesis(left, right - 1, s, answer);
    s.pop_back();
}

int main()
{
    int n = 3;
    // vector ans is created to store all the possible valid
    // combinations of the parentheses.
    vector<string> ans;
    string s;
    // initially we are passing the counts of open and close
    // as 0, and the string s as an empty string.
    generateParenthesis(n, n, s, ans);
    // Now, here we print out all the combinations.
    for (auto k : ans) {
        cout << k << endl;
    }
    return 0;
}
Java
// Java program to print all the combinations of balanced
// parenthesis.
import java.util.*;

class GFG {

    // Function to generate all the combinations of
    // balanced parenthesis
    static void generateParenthesis(int left, int right,
                                    String s,
                                    List<String> answer)
    {

        // terminate
        if (left == 0 && right == 0) {
            answer.add(s);
        }

        if (left > right || left < 0 || right < 0) {
            // wrong
            return;
        }

        s += "{";
        generateParenthesis(left - 1, right, s, answer);
        s = s.substring(0, s.length() - 1);

        s += "}";
        generateParenthesis(left, right - 1, s, answer);
        s = s.substring(0, s.length() - 1);
    }

    public static void main(String[] args)
    {
        int n = 3;

        // vector ans is created to store all the possible
        // valid combinations of the parentheses.
        List<String> ans = new ArrayList<>();
        String s = "";

        // initially we are passing the counts of open and
        // close as 0, and the string s as an empty string.
        generateParenthesis(n, n, s, ans);

        // Now, here we print out all the combinations.
        for (String k : ans) {
            System.out.println(k);
        }
    }
}

// This code is contributed by Ajax
Python
def generateParenthesis(left, right, s, answer):
    # terminate
    if left == 0 and right == 0:
        answer.append(s)
    if left > right or left < 0 or right < 0:
        # wrong
        return
    s += '{'
    generateParenthesis(left - 1, right, s, answer)
    s = s[:-1]
    s += '}'
    generateParenthesis(left, right - 1, s, answer)
    s = s[:-1]


n = 3
# list ans is created to store all the possible valid
# combinations of the parentheses.
ans = []
s = ""
# initially we are passing the counts of open and close
# as 0, and the string s as an empty string.
generateParenthesis(n, n, s, ans)
# Now, here we print out all the combinations.
for k in ans:
    print(k)
C#
using System;
using System.Collections.Generic;

namespace GFG {
public class Program {
    // Function to generate all the combinations of
    // balanced parenthesis
    static void generateParenthesis(int left, int right,
                                    string s,
                                    List<string> answer)
    {
        // terminate
        if (left == 0 && right == 0) {
            answer.Add(s);
        }

        if (left > right || left < 0 || right < 0) {
            // wrong
            return;
        }

        s += "{";
        generateParenthesis(left - 1, right, s, answer);
        s = s.Substring(0, s.Length - 1);

        s += "}";
        generateParenthesis(left, right - 1, s, answer);
        s = s.Substring(0, s.Length - 1);
    }

    // Driver code
    public static void Main(string[] args)
    {
        int n = 3;

        // vector ans is created to store all the possible
        // valid combinations of the parentheses.
        List<string> ans = new List<string>();
        string s = "";

        // initially we are passing the counts of open and
        // close as 0, and the string s as an empty string.
        generateParenthesis(n, n, s, ans);

        // Now, here we print out all the combinations.
        foreach(string k in ans) { Console.WriteLine(k); }
    }
}
}
// This code contributed by SRJ
JavaScript
<script>
  function generateParenthesis(left, right, s, answer) {
    // terminate
    if (left == 0 && right == 0) {
      answer.push(s);
    }

    if (left > right || left < 0 || right < 0) {
      // wrong
      return;
    }

    s += '{';
    generateParenthesis(left - 1, right, s, answer);
    s = s.slice(0, -1);

    s += '}';
    generateParenthesis(left, right - 1, s, answer);
    s = s.slice(0, -1);
  }

  function main() {
    let n = 3;
    // array ans is created to store all the possible valid
    // combinations of the parentheses.
    let ans = [];
    let s = '';
    // initially we are passing the counts of open and close
    // as 0, and the string s as an empty string.
    generateParenthesis(n, n, s, ans);
    // Now, here we print out all the combinations.
    for (let k of ans) {
      console.log(k);
    }
  }

  main();
</script>

Output
{{{}}}
{{}{}}
{{}}{}
{}{{}}
{}{}{}

Time Complexity: O(2^n)
Auxiliary Space:  O(n)

Please write comments if you find the above codes/algorithms incorrect, or find better ways to solve the same problem.
 



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
itertools.combinations() module in Python to print all possible combinations
Given an array of size n, generate and print all possible combinations of r elements in array. Examples: Input : arr[] = [1, 2, 3, 4], r = 2Output : [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]This problem has existing recursive solution please refer Print all possible combinations of r elements in a given array of size n link. We will solve th
2 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
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
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
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
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
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
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
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
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
Print all combinations of points that can compose a given number
You can win three kinds of basketball points, 1 point, 2 points, and 3 points. Given a total score of n, print out all the combinations to compose n. Examples: For n = 1, the program should print following: 1 For n = 2, the program should print following: 1 1 2 For n = 3, the program should print following: 1 1 1 1 2 2 1 3 For n = 4, the program sh
9 min read
Print all the combinations of a string in lexicographical order
Given a string str, print of all the combinations of a string in lexicographical order.Examples: Input: str = "ABC" Output: A AB ABC AC ACB B BA BAC BC BCA C CA CAB CB CBA Input: ED Output: D DE E ED Approach: Count the occurrences of all the characters in the string using a map, then using recursion all the possible combinations can be printed. St
9 min read
Print all possible combinations of the string by replacing '$' with any other digit from the string
Given a number as a string where some of the digits are replaced by a '$', the task is to generate all possible number by replacing the '$' with any of the digits from the given string.Examples: Input: str = "23$$" Output: 2322 2323 2332 2333Input: str = "$45" Output: 445 545 Approach: Find all the combinations of the string by replacing the charac
15+ min read
Print all combinations generated by characters of a numeric string which does not exceed N
Given a numeric string S of length M and an integer N, the task is to find all distinct combinations of S (repetitions allowed) that are at most N. Examples: Input: S = "124", N = 100Output: 1, 11, 12, 14, 2, 21, 22, 24, 4, 41, 42, 44Explanation: Combinations "111", "112", "122", "124", "412" are greater than 100. Therefore, these combinations are
7 min read
Print all unique combinations of setting N pieces on an NxN board
Given an integer N, the task is to print all the unique combinations of putting N pieces in an NxN board. Note: Print ("*") for pieces and ("-") for an empty space. Example: Input: N = 2Output:* *- - * -* - * -- * - ** - - *- * - -* *Explanation: The total number of empty spaces are 2*2=4 and the pieces to be set is 2 so there are 4C2 combinations
8 min read
Print all combinations | Set-2
Given an array of size n, generate and print all possible combinations of r elements in the array. Example: Input: arr=[1,2,3,4], r=2 Output: 1 2 1 3 1 4 2 3 2 4 3 4 Input: arr=[1,2,3,4], r=3 Output: 1 2 3 1 2 4 1 3 4 2 3 4 Method 1 (Fix Elements and Recur) The idea is to start from first index (index = 0) , one by one fix elements at this index an
15+ min read
Print all combinations | Set-1
Given two numbers n and k, you have to print all possible combinations of k numbers from 1...n. Examples: Input : n = 4 k = 2 Output: 1 2 1 3 1 4 2 3 2 4 3 4 Input : n = 5 k = 3 Output : 1 2 3 1 2 4 1 2 5 1 3 4 1 3 5 1 4 5 2 3 4 2 3 5 2 4 5 3 4 5 Print all combinations using Backtracking:The idea is to use a recursive approach to construct these co
6 min read
Print all combinations of factors (Ways to factorize)
Write a program to print all the combinations of factors of given number n. Examples: Input : 16Output :2 2 2 2 2 2 4 2 8 4 4 Input : 12Output : 2 2 3 2 6 3 4To solve this problem we take one array of array of integers or list of list of integers to store all the factors combination possible for the given n. So, to achieve this we can have one recu
12 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
Print combinations of distinct numbers which add up to give sum N
Given a positive integer N, the task is to find out all the combinations of positive integers that add upto the given integer N. The program should print only combinations, not permutations and all the integers in a combination must be distinct. For example, for input 3, either 1, 2 or 2, 1 should be printed and 1, 1, 1 must not be printed as the i
8 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
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
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
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
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
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