![]() |
VOOZH | about |
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).
Below are the implementations to find count of Dyck Paths (or n'th Catalan number).
Number of Dyck Paths is 14
Time complexity: O(n).
Auxiliary space: O(1).
Exercise :
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.
Number of Dyck paths is 4: 14
Time complexity: O(n).
Auxiliary space: O(1).