
Print only those distinct strings that can be formed by removing the minimum number of parentheses.
If the string is already balanced, return the original string.
(()()()
Expected strings are:
[ (()()), (())(), ()()() ]
The first line contains an integer 'T' which denotes the number of test cases or queries to be run.
The first line of each test case contains a string ‘S’ which contains the parentheses.
For each case, If the returned strings are correct then the output will be 1, else 0.
The output of each test case will be printed on a separate line.
You can return strings in any order.
You do not need to input or print anything, it has already been taken care of. Just implement the given function.
1 <= T <= 5
1 <= |S| <= 15
Timit Limit: 1 sec
Here, we will use the concept of Backtracking and Breadth-First Search. As we need to generate all possible output, we can backtrack among all states by removing one opening or closing bracket and check if they are valid or not. If invalid, then we can add the removed bracket back and go for the next state. We will use BFS for moving through states as the use of BFS will only remove the minimal number of brackets because we traverse into states level-wise and each level corresponds to one extra bracket removal.
Maximum Island Size in a Binary Tree
Equal Subtree Sums
Sorted Doubly Linked List to Balanced BST
Longest Substring with K-Repeating Characters
Expression Add Operators