![]() |
VOOZH | about |
Given a string S of length N, consisting of only opening '(' and closing ')' parenthesis. The task is to find all indices 'K' such that S[K...N-1] + S[0...K-1] is a regular parenthesis.
A regular parentheses string is either empty (""), "(" + str1 + ")", or str1 + str2, where str1 and str2 are regular parentheses strings.
For example: "", "()", "(())()", and "(()(()))" are regular parentheses strings.
Examples:
Input: str = ")()("
Output: 2
Explanation:
For K = 1, S = ()(), which is regular.
For K = 3, S = ()(), which is regular.
Input: S = "())("
Output: 1
Explanation:
For K = 3, S = (()), which is regular.
Naive Approach: The naive approach is to split the given string str at every possible index(say K) and check whether str[K, N-1] + str[0, K-1] is palindromic or not. If yes then print that particular value of K.
Time Complexity: O(N2)
Auxiliary Space: O(1)
Efficient Approach: The idea is to observe that if at any index(say K) where the count of closing brackets is greater than the count of opening brackets then that index is the possible index of splitting the string. Below are the steps:
Below is the implementation of the above approach:
2
Time Complexity: O(N), where N is the length of the string.
Auxiliary Space: O(N), where N is the length of the string.