Given N bracket sequences, the task is to find the number of pairs of bracket sequences by joining which can be obtained a balanced bracket sequence as a whole. A bracket parentheses sequence can only be a part of a single pair.
Examples:
Input: { ")())", ")", "((", "((", "(", ")", ")"}
Output: 2
Bracket sequence {1, 3} and {5, 6}
Input: {"()", "(())", "(())", "()"}
Output: 2
Since all brackets are balanced, hence we can form 2 pairs with 4.
Approach: The following steps can be followed to solve the above problem:
- Count required opening and closing brackets, of individuals.
- If required closing brackets > 0 and opening brackets are 0, then hash the bracket's required closing number.
- Similarly, if required opening brackets > 0 and closing brackets are 0, then hash the bracket's required opening number.
- Count the balanced bracket sequences.
- Add (number of balanced bracket sequences/2) to the number of pairs.
- For every number of sequences that requires same number of opening brackets, min(hash[open], hash[close]) will be added to the number of pairs
Below is the implementation of the above approach:
Complexity Analysis:
- Time Complexity: O(N*M), as we are using nested loops to traverse N*M times.Where N is the number of strings in the bracks and M is the maximum length of the strings present in the bracks.
- Auxiliary Space: O(N), as we are using extra space for the map. Where N is the number of strings in the bracks.