Consider a n x n grid with indexes of top left corner as (0, 0). Dyck path is a staircase walk from bottom left, i.e., (n-1, 0) to top right, i.e., (0, n-1) that lies above the diagonal cells (or cells on line from bottom left to top right).
The task is to count the number of Dyck Paths from (n-1, 0) to (0, n-1).
Examples :Â
Input : n = 1 Output : 1 Input : n = 2 Output : 2 Input : n = 3 Output : 5 Input : n = 4 Output : 14
Â
The number of Dyck paths from (n-1, 0) to (0, n-1) can be given by the Catalan numberC(n).
Â
We strongly recommend that you click here and practice it, before moving on to the solution.
Below are the implementations to find count of Dyck Paths (or n’th Catalan number).
C++
// C++ program to count // number of Dyck Paths#include<iostream>using namespace std;Â
// Returns count Dyck // paths in n x n gridint countDyckPaths(unsigned int n){    // Compute value of 2nCn    int res = 1;    for (int i = 0; i < n; ++i)    {        res *= (2 * n - i);        res /= (i + 1);    }Â
    // return 2nCn/(n+1)    return res / (n+1);}Â
// Driver Codeint main(){Â Â Â Â int n = 4;Â Â Â Â cout << "Number of Dyck Paths is "Â Â Â Â Â Â Â Â Â << countDyckPaths(n);Â Â Â Â return 0;} |
Java
// Java program to count// number of Dyck Pathsclass GFG{    // Returns count Dyck     // paths in n x n grid    public static int countDyckPaths(int n)    {        // Compute value of 2nCn        int res = 1;        for (int i = 0; i < n; ++i)        {            res *= (2 * n - i);            res /= (i + 1);        }Â
        // return 2nCn/(n+1)        return res / (n + 1);    }Â
    // Driver code    public static void main(String args[])    {        int n = 4;        System.out.println("Number of Dyck Paths is " +                                    countDyckPaths(n));    }} |
Python3
# Python3 program to count # number of Dyck PathsÂ
# Returns count Dyck # paths in n x n griddef countDyckPaths(n):         # Compute value of 2nCn    res = 1    for i in range(0, n):        res *= (2 * n - i)        res /= (i + 1)Â
    # return 2nCn/(n+1)    return res / (n+1)Â
# Driver Coden = 4print("Number of Dyck Paths is ",    str(int(countDyckPaths(n))))Â
# This code is contributed by# Prasad Kshirsagar |
Javascript
<script>Â
// JavaScript program to count// number of Dyck PathsÂ
    // Returns count Dyck     // paths in n x n grid    function countDyckPaths(n)    {             // Compute value of 2nCn        let res = 1;        for (let i = 0; i < n; ++i)        {            res *= (2 * n - i);            res /= (i + 1);        }           // return 2nCn/(n+1)        return res / (n + 1);    }Â
// Driver CodeÂ
        let n = 4;        document.write("Number of Dyck Paths is " +                                    countDyckPaths(n));         // This code is contributed by target_2.</script> |
C#
// C# program to count// number of Dyck Pathsusing System;Â
class GFG {         // Returns count Dyck     // paths in n x n grid    static int countDyckPaths(int n)    {                 // Compute value of 2nCn        int res = 1;        for (int i = 0; i < n; ++i)        {            res *= (2 * n - i);            res /= (i + 1);        }Â
        // return 2nCn/(n+1)        return res / (n + 1);    }Â
    // Driver code    public static void Main()    {        int n = 4;        Console.WriteLine("Number of "                  + "Dyck Paths is " +                   countDyckPaths(n));    }}Â
// This code is contributed by anuj_67. |
PHP
<?php// PHP program to count // number of Dyck PathsÂ
// Returns count Dyck // paths in n x n gridfunction countDyckPaths( $n){    // Compute value of 2nCn    $res = 1;    for ( $i = 0; $i < $n; ++$i)    {        $res *= (2 * $n - $i);        $res /= ($i + 1);    }Â
    // return 2nCn/(n+1)    return $res / ($n + 1);}Â
// Driver Code$n = 4;echo "Number of Dyck Paths is " , Â Â Â Â Â Â Â Â Â Â Â Â Â Â countDyckPaths($n);Â
// This code is contributed by anuj_67.?> |
Number of Dyck Paths is 14
Time complexity: O(n).
Auxiliary space: O(1).
Exercise :Â Â
- Find number of sequences of 1 and -1 such that every sequence follows below constraints :Â
a) The length of a sequence is 2nÂ
b) There are equal number of 1’s and -1’s, i.e., n 1’s, n -1sÂ
c) Sum of prefix of every sequence is greater than or equal to 0. For example, 1, -1, 1, -1 and 1, 1, -1, -1 are valid, but -1, -1, 1, 1 is not valid. - Number of paths of length m + n from (m-1, 0) to (0, n-1) that are restricted to east and north steps.
Approach 2:-approach to count the number of Dyck paths –In this implementation, we generate all possible Dyck paths of length n by generating all binary numbers with n bits. We then traverse through each bit in the binary representation of the number and update the depth accordingly. If at any point the depth becomes negative, then the path is not a Dyck path, so we break out of the loop. If we reach the end of the path and the depth is zero, then the path is a Dyck path, so we increment the count. Finally, we return the count of Dyck paths.
C++
#include <iostream>Â
using namespace std;Â
// Function to calculate the factorial of a given numberint factorial(int n) {Â Â Â Â int fact = 1;Â Â Â Â for (int i = 1; i <= n; i++) {Â Â Â Â Â Â Â Â fact *= i;Â Â Â Â }Â Â Â Â return fact;}Â
// Function to calculate the number of Dyck paths of length n using the 2 approachint dyck_paths_2(int n) {Â Â Â Â int numerator = factorial(2 * n);Â Â Â Â int denominator = factorial(n + 1) * factorial(n);Â Â Â Â return numerator / denominator;}Â
int main() {Â Â Â Â int n = 4;Â
    cout << "Number of Dyck paths is " << n << ": " << dyck_paths_2(n) << endl;Â
    return 0;} |
Java
import java.util.*;Â
public class DyckPaths {Â
  // Function to calculate the factorial of a given number  public static int factorial(int n)  {    int fact = 1;    for (int i = 1; i <= n; i++) {      fact *= i;    }    return fact;  }Â
  // Function to calculate the number of Dyck paths of  // length n using the 2 approach  public static int dyck_paths_2(int n)  {    int numerator = factorial(2 * n);    int denominator = factorial(n + 1) * factorial(n);    return numerator / denominator;  }Â
  public static void main(String[] args)  {    int n = 4;Â
    System.out.println("Number of Dyck paths is " + n                       + ": " + dyck_paths_2(n));  }}Â
// This code is contributed by Prajwal Kandekar |
Python3
# Function to calculate the factorial of a given numberdef factorial(n):    fact = 1    for i in range(1, n + 1):        fact *= i    return factÂ
# Function to calculate the number of Dyck paths of length n using the 2 approachdef dyck_paths_2(n):Â Â Â Â numerator = factorial(2 * n)Â Â Â Â denominator = factorial(n + 1) * factorial(n)Â Â Â Â return numerator // denominatorÂ
if __name__ == '__main__':Â Â Â Â n = 4Â Â Â Â print("Number of Dyck paths is {}: {}".format(n, dyck_paths_2(n))) |
Javascript
function factorial(n) {Â Â let fact = 1;Â Â for (let i = 1; i <= n; i++) {Â Â Â Â fact *= i;Â Â }Â Â return fact;}Â
function dyckPaths2(n) {Â Â const numerator = factorial(2 * n);Â Â const denominator = factorial(n + 1) * factorial(n);Â Â return numerator / denominator;}Â
const n = 4;console.log(`Number of Dyck paths is ${n}: ${dyckPaths2(n)}`); |
C#
using System;Â
class Program {    // Function to calculate the factorial of a given number    static int Factorial(int n)    {        int fact = 1;        for (int i = 1; i <= n; i++) {            fact *= i;        }        return fact;    }Â
    // Function to calculate the number of Dyck paths of    // length n using the 2 approach    static int DyckPaths2(int n)    {        int numerator = Factorial(2 * n);        int denominator = Factorial(n + 1) * Factorial(n);        return numerator / denominator;    }Â
    static void Main(string[] args)    {        int n = 4;Â
        Console.WriteLine("Number of Dyck paths is " + n                          + ": " + DyckPaths2(n));    }} |
Number of Dyck paths is 4: 14
Time complexity: O(n).
Auxiliary space: O(1).
This article is contributed by Aditya Chatterjee. If you like neveropen and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the neveropen main page and help other Geeks.
 Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

