Given a string str of length N, the task is to find the number of ways to insert only 2 pairs of parentheses into the given string such that the resultant string is still valid.
Input: str = “ab”
((a))b, ((a)b), ((ab)), (a)(b), (a(b)), a((b))
which are a total of 6 ways.
Input: str = “aab”
Approach: it can be observed that for the lengths of the string 1, 2, 3, …, N a series will be formed as 1, 6, 20, 50, 105, 196, 336, 540, … whose Nth term is (N + 1)2 * ((N + 1)2 – 1) / 12.
Below is the implementation of the above approach:
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Count pairs of parentheses sequences such that parentheses are balanced
- Pairs involved in Balanced Parentheses
- Number of ways to partition a string into two balanced subsequences
- Count of ungrouped characters after dividing a string into K groups of distinct characters
- Check if the Depth of Parentheses is correct in the given String
- Number of ways to insert a character to increase the LCS by one
- Ways of dividing a group into two halves such that two elements are in different groups
- Check if a string can be split into two strings with same number of K-frequent characters
- Partition string into two subtrings having maximum number of common non-repeating characters
- Find the number of valid parentheses expressions of given length
- Minimum number of Parentheses to be added to make it valid
- Count of ways to split given string into two non-empty palindromes
- Ways to form n/2 pairs such that difference of pairs is minimum
- Count number of ways to divide an array into two halves with same sum
- Rearrange the characters of the string such that no two adjacent characters are consecutive English alphabets
- Print all combinations of balanced parentheses
- Remove Invalid Parentheses
- Check for balanced parentheses in an expression | O(1) space | O(N^2) time complexity
- Cost to Balance the parentheses
- Check for balanced parentheses in an expression | O(1) space
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.