![]() |
VOOZH | about |
Given an integer N, the task is to find the number of distinct bracket sequences that can be formed using 2 * N brackets such that the sequence is not N-periodic.
A bracket sequence str of length 2 * N is said to be N-periodic if the sequence can be split into two equal substrings having same regular bracket sequence.
A regular bracket sequence is a sequence in the following way:
- An empty string is a regular bracket sequence.
- If s & t are regular bracket sequences, then s + t is a regular bracket sequence.
Examples:
Input: N = 3
Output: 5
Explanation:
There will be 5 distinct regular bracket sequences of length 2 * N = ()()(), ()(()), (())(), (()()), ((()))
Now, none of the sequences are N-periodic. Therefore, the output is 5.Input: N = 4
Output: 12
Explanation:
There will be 14 distinct regular bracket sequences of length 2*N which are
()()()(), ()()(()), ()(())(), ()(()()), ()((())), (())()(), (())(()), (()())(), (()()()), (()(())), ((()))(), ((())()), ((()())), (((())))
Out of these 14 regular sequences, two of them are N periodic which are
()()()() and (())(()). They have a period of N.
Therefore, the distinct regular bracket sequences of length 2 * N which are not N-periodic are 14 - 2 = 12.
Approach: The idea is to calculate the total number of regular bracket sequences possible of length 2 * N and then to subtract the number of bracket sequences which are N-periodic from it. Below are the steps:
Below is the implementation of the above approach:
12
Time Complexity: O(N)
Auxiliary Space: O(1)