Find the number of valid parentheses expressions of given length Last Updated : 07 Nov, 2024 Summarize Comments Improve Suggest changes Share Like Article Like Report Given a number n, the task is to find the number of valid parentheses expressions of that length. Examples : Input: 2Output: 1 Explanation: There is only possible valid expression of length 2, "()"Input: 4Output: 2 Explanation: Possible valid expression of length 4 are "(())" and "()()" Input: 6Output: 5Explanation: Possible valid expressions are ((())), ()(()), ()()(), (())() and (()())Table of ContentUsing recursion - O(2 ^ n) Time and O(1) SpaceUsing Dynamic programming (Catalan Numbers) - O(n) Time and O(1) SpaceUsing recursion - O(2 ^ n) Time and O(1) SpaceThe idea is to use recursion to find number of valid parentheses expressions of given length. first, check if n is odd, returns 0 because valid arrangements are not possible. Then, it recursively explores all possible arrangements by adding left and right parentheses, only proceeding if the number of left parentheses doesn’t exceed the number of right ones). Whenever both left and right parentheses reach zero, a valid combination is found. C++ // C++ program to find valid paranthesisations // of length n #include <bits/stdc++.h> using namespace std; // Helper function to recursively count // valid parentheses arrangements int helper(int left, int right, int &ans) { // If no more left and right parentheses // are remaining, a valid combination is found if (left == 0 && right == 0) { ans++; return ans; } // If more right parentheses than left, // return (invalid state) if (left > right) { return 0; } // Try adding a left parenthesis if available if (left > 0) { helper(left - 1, right, ans); } // Try adding a right parenthesis // if available if (right > 0) { helper(left, right - 1, ans); } return ans; } // Function to count valid parentheses // arrangements of length n int findWays(int n) { // If n is odd, no valid arrangements possible if (n % 2 == 1) return 0; int ans = 0; return helper(n / 2, n / 2, ans); } int main() { int n = 6; int res = findWays(n); cout << res << endl; return 0; } Java // Java program to find valid parenthesizations // of length n import java.util.*; class GfG { // Helper function to recursively count valid // parentheses arrangements static int helper(int left, int right, int[] ans) { // If no more left and right parentheses // are remaining, a valid combination is found if (left == 0 && right == 0) { ans[0]++; return ans[0]; } // If more right parentheses than left, return // (invalid state) if (left > right) { return 0; } // Try adding a left parenthesis if available if (left > 0) { helper(left - 1, right, ans); } // Try adding a right parenthesis if available if (right > 0) { helper(left, right - 1, ans); } return ans[0]; } // Function to count valid parentheses arrangements of // length n static int findWays(int n) { // If n is odd, no valid arrangements // possible if (n % 2 == 1) return 0; int[] ans = { 0 }; return helper(n / 2, n / 2, ans); } public static void main(String[] args) { int n = 6; int res = findWays(n); System.out.println(res); } } Python # Python program to find valid parenthesizations of length n # Helper function to recursively count # valid parentheses arrangements def helper(left, right, ans): # If no more left and right parentheses are # remaining, a valid combination is found if left == 0 and right == 0: ans[0] += 1 return ans[0] # If more right parentheses than left, # return (invalid state) if left > right: return 0 # Try adding a left parenthesis if available if left > 0: helper(left - 1, right, ans) # Try adding a right parenthesis if available if right > 0: helper(left, right - 1, ans) return ans[0] # Function to count valid parentheses # arrangements of length n def findWays(n): # If n is odd, no valid arrangements # possible if n % 2 == 1: return 0 ans = [0] return helper(n // 2, n // 2, ans) n = 6 res = findWays(n) print(res) C# // C# program to find valid parenthesizations // of length n using System; class GfG { // Helper function to recursively count // valid parentheses arrangements static int Helper(int left, int right, ref int ans) { // If no more left and right parentheses // are remaining, a valid combination is found if (left == 0 && right == 0) { ans++; return ans; } // If more right parentheses than left, return // (invalid state) if (left > right) { return 0; } // Try adding a left parenthesis if available if (left > 0) { Helper(left - 1, right, ref ans); } // Try adding a right parenthesis if available if (right > 0) { Helper(left, right - 1, ref ans); } return ans; } // Function to count valid parentheses arrangements of // length n static int FindWays(int n) { // If n is odd, no valid arrangements // possible if (n % 2 == 1) return 0; int ans = 0; return Helper(n / 2, n / 2, ref ans); } static void Main() { int n = 6; int res = FindWays(n); Console.WriteLine(res); } } JavaScript // JavaScript program to find valid parenthesizations of // length n // Helper function to recursively count // valid parentheses arrangements function helper(left, right, ans) { // If no more left and right parentheses are // remaining, a valid combination is found if (left === 0 && right === 0) { ans.count++; return ans.count; } // If more right parentheses than // left, return (invalid // state) if (left > right) { return 0; } // Try adding a left parenthesis if available if (left > 0) { helper(left - 1, right, ans); } // Try adding a right parenthesis if available if (right > 0) { helper(left, right - 1, ans); } return ans.count; } // Function to count valid parentheses arrangements of // length n function findWays(n) { // If n is odd, no valid arrangements possible if (n % 2 === 1) return 0; const ans = {count : 0}; return helper(n / 2, n / 2, ans); } const n = 6; const res = findWays(n); console.log(res); Output5 Using Dynamic programming (Catalan Numbers) - O(n) Time and O(1) SpaceThis is mainly an application of Catalan Numbers. Total possible valid expressions for input n is n/2'th Catalan Number if n is even and 0 if n is odd. Algorithm:Calculate the binomial coefficient C(2n,n) using a combinatorial formula, optimized to reduce computational steps by leveraging symmetry C(n,k) = C(n,n-k). Use the binomial coefficient to compute the nth Catalan number as C(2n,n)/(n+1). This represents the number of valid ways to arrange pairs of parentheses.Check if n is odd; if so, it's impossible to have balanced parentheses, and return 0.For even n, compute the (n/2)th Catalan number, which gives the total count of valid balanced parentheses arrangements of length n. C++ // C++ program to find valid paranthesisations // of length n #include <bits/stdc++.h> using namespace std; // Returns value of Binomial Coefficient C(n, k) int binomialCoeff(int n, int k) { int res = 1; // Since C(n, k) = C(n, n-k) if (k > n - k) k = n - k; // Calculate value of [n*(n-1)*---*(n-k+1)] / [k*(k-1)*---*1] for (int i = 0; i < k; ++i) { res *= (n - i); res /= (i + 1); } return res; } // A Binomial coefficient based function to // find nth catalan number in O(n) time int catalan(int n) { // Calculate value of 2nCn int c = binomialCoeff(2 * n, n); // return 2nCn/(n+1) return c / (n + 1); } // Function to find possible ways to put balanced // parenthesis in an expression of length n int findWays(int n) { // If n is odd, not possible to // create any valid parentheses if (n & 1) return 0; // Otherwise return n/2'th Catalan Number return catalan(n / 2); } int main() { int n = 6; cout << findWays(n); return 0; } Java // Java program to find valid // parenthesizations of length n class GfG { // Returns value of Binomial Coefficient C(n, k) static int binomialCoeff(int n, int k) { int res = 1; // Since C(n, k) = C(n, n-k) if (k > n - k) k = n - k; // Calculate value of [n*(n-1)*---*(n-k+1)] / [k*(k-1)*---*1] for (int i = 0; i < k; ++i) { res *= (n - i); res /= (i + 1); } return res; } // A Binomial coefficient based function to // find nth catalan number in O(n) time static int catalan(int n) { // Calculate value of 2nCn int c = binomialCoeff(2 * n, n); // return 2nCn/(n+1) return (int) (c / (n + 1)); } // Function to find possible ways to put balanced // parenthesis in an expression of length n static int findWays(int n) { // If n is odd, not possible to // create any valid parentheses if ((n & 1) == 1) return 0; // Otherwise return n/2'th Catalan // Number return catalan(n / 2); } public static void main(String[] args) { int n = 6; System.out.println(findWays(n)); } } Python # Python program to find valid parenthesizations of length n # Returns value of Binomial Coefficient C(n, k) def binomialCoeff(n, k): res = 1 # Since C(n, k) = C(n, n-k) if k > n - k: k = n - k # Calculate value of [n*(n-1)*---*(n-k+1)] / [k*(k-1)*---*1] for i in range(k): res *= (n - i) res //= (i + 1) return res # A Binomial coefficient based function to # find nth catalan number in O(n) time def catalan(n): # Calculate value of 2nCn c = binomialCoeff(2 * n, n) # return 2nCn/(n+1) return c // (n + 1) # Function to find possible ways to put balanced # parenthesis in an expression of length n def findWays(n): # If n is odd, not possible to # create any valid parentheses if n & 1: return 0 # Otherwise return n/2'th Catalan # Number return catalan(n // 2) if __name__ == "__main__": n = 6 print(findWays(n)) C# // C# program to find valid parenthesizations // of length n using System; class GfG { // Returns value of Binomial Coefficient C(n, k) static int BinomialCoeff(int n, int k) { int res = 1; // Since C(n, k) = C(n, n-k) if (k > n - k) k = n - k; // Calculate value of [n*(n-1)*---*(n-k+1)] / // [k*(k-1)*---*1] for (int i = 0; i < k; ++i) { res *= (n - i); res /= (i + 1); } return res; } // A Binomial coefficient based function to // find nth catalan number in O(n) time static int Catalan(int n) { // Calculate value of 2nCn int c = BinomialCoeff(2 * n, n); // return 2nCn/(n+1) return (int)(c / (n + 1)); } // Function to find possible ways to put balanced // parenthesis in an expression of length n static int FindWays(int n) { // If n is odd, not possible to // create any valid parentheses if ((n & 1) == 1) return 0; // Otherwise return n/2'th Catalan // Number return Catalan(n / 2); } static void Main() { int n = 6; Console.WriteLine(FindWays(n)); } } JavaScript // JavaScript program to find valid parenthesizations of // length n // Returns value of Binomial Coefficient C(n, k) function binomialCoeff(n, k) { let res = 1; // Since C(n, k) = C(n, n-k) if (k > n - k) k = n - k; // Calculate value of [n*(n-1)*---*(n-k+1)] / // [k*(k-1)*---*1] for (let i = 0; i < k; ++i) { res *= (n - i); res /= (i + 1); } return res; } // A Binomial coefficient based function to // find nth catalan number in O(n) time function catalan(n) { // Calculate value of 2nCn let c = binomialCoeff(2 * n, n); // return 2nCn/(n+1) return Math.floor(c / (n + 1)); } // Function to find possible ways to put balanced // parenthesis in an expression of length n function findWays(n) { // If n is odd, not possible to // create any valid parentheses if (n & 1) return 0; // Otherwise return n/2'th Catalan Number return catalan(n / 2); } let n = 6; console.log(findWays(n)); Output5 Comment More infoAdvertise with us Next Article Find the number of valid parentheses expressions of given length K kartik Improve Article Tags : Mathematical DSA catalan Parentheses-Problems Practice Tags : Mathematical Similar Reads Mastering Bracket Problems for Competitive Programming Bracket problems in programming typically refer to problems that involve working with parentheses, and/or braces in expressions or sequences. It typically refers to problems related to the correct and balanced usage of parentheses, and braces in expressions or code. These problems often involve chec 4 min read Check for balanced with only one type of brackets Given a string str of length N, consisting of '(' and ')' only, the task is to check whether it is balanced or not.Examples:Input: str = "((()))()()" Output: BalancedInput: str = "())((())" Output: Not Balanced Approach 1: Declare a Flag variable which denotes expression is balanced or not.Initialis 9 min read Valid Parentheses in an Expression Given a string s representing an expression containing various types of brackets: {}, (), and [], the task is to determine whether the brackets in the expression are balanced or not. A balanced expression is one where every opening bracket has a corresponding closing bracket in the correct order.Exa 8 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 : 6The idea is take value of op 9 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 10 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. "( 6 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 th 7 min read Minimum number of Parentheses to be added to make it valid Given a string S of parentheses '(' or ')' where, 0\leq len(S)\leq 1000 . 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: s 9 min read Minimum bracket reversals 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: s = "}{{}}{{{"Output: 3Explanation: We need to reverse minimum 3 brackets to make "{{{}}{}}". Input: s = "{{"Output: 1Explanation: 15+ min read Find the number of valid parentheses expressions of given length Given a number n, the task is to find the number of valid parentheses expressions of that length. Examples : Input: 2Output: 1 Explanation: There is only possible valid expression of length 2, "()"Input: 4Output: 2 Explanation: Possible valid expression of length 4 are "(())" and "()()" Input: 6Outp 11 min read Like