I came across an interesting codding problem at https://www.geeksforgeeks.org/number-of-ways-to-insert-two-pairs-of-parentheses-into-a-string-of-n-characters/
Problem:
Problem:
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.Example:
Input: str = “ab”Output: 6((a))b, ((a)b), ((ab)), (a)(b), (a(b)), a((b))which are a total of 6 ways.Solution:
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.The solution is good but the page does not provide derivation of the formula which is base of the solution. I tried to derive the formula on my own and this is what I came up with:
- There are N+1 places where parenthesis can be placed. One in the beginning, N-1 in middle and one at end. So there are ((N + 1)4 )/4 ways to place the parenthesis. We can place multiple parenthesis at same location, one opening parenthesis can be replaced with another opening parenthesis and closing parenthesis can be replaced with other closing parenthesis therefore we divided by 4.
- Some of the combinations counted in previous step are invalid so we need to subtract them.
- All four parenthesis at same location is not a valid case there are (N+1)/4 such combinations so we need to subtract them.
- Three parenthesis being at one location and one being at one location is also not a valid combination. There are (N+1)*N/4 such combinations so we need to subtract them.
- After the above considerations We come up with (N + 1)2 * ((N + 1)2 – 1) / 4 ways.
- Now if you think closely out of following 6 possible combinations of parenthesis only first two are valid. You ignore string character in between parenthesis.
- (())
- ()()
- )()(
- )(()
- ))((
- ())(
- So we need to divide by 3 to get valid ways of putting parenthesis. So we get the final formula as (N + 1)2 * ((N + 1)2 – 1) / 12.
No comments:
Post a Comment