Open In App

Find the number of valid parentheses expressions of given length

Last Updated : 07 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a number n, the task is to find the number of valid parentheses expressions of that length. 
Examples : 

Input: 2
Output: 1
Explanation: There is only possible valid expression of length 2, “()”

Input: 4
Output: 2
Explanation: Possible valid expression of length 4 are “(())” and “()()”

Input: 6
Output: 5
Explanation: Possible valid expressions are ((())), ()(()), ()()(), (())() and (()())

Using recursion – O(2 ^ n) Time and O(1) Space

The 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);

Output
5

Using Dynamic programming (Catalan Numbers) – O(n) Time and O(1) Space

This 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));

Output
5


Next Article
Practice Tags :

Similar Reads