VOOZH about

URL: https://www.geeksforgeeks.org/dsa/dyck-path/

⇱ Dyck path - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Dyck path

Last Updated : 23 Jul, 2025

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


 

👁 dyckpaths


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


Output
Number of Dyck Paths is 14

Time complexity: O(n).
Auxiliary space: O(1).

Exercise :  

  1. 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.
  2. 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.


Output
Number of Dyck paths is 4: 14

Time complexity: O(n).
Auxiliary space: O(1).


 

Comment
Article Tags: