Skip to content

Commit a5e0278

Browse files
committed
updated explanation, reusing same code to find invalid parenthesis
1 parent 1da354e commit a5e0278

File tree

1 file changed

+13
-2
lines changed

1 file changed

+13
-2
lines changed

backtracking/removeInvalidParentheses.java

+13-2
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,17 @@ public List<String> removeInvalidParentheses(String s) {
55
return output;
66
}
77

8+
/*
9+
We keep the openParen as '(' and closed as ')', we try to find an extra closed ')' that would make an invalid parenthesis
10+
and we will remove it by skipping it and then keep checking for invalid parenthesis with iStart value as next i value and
11+
jStart value as the index of j we removed the invalid parenthesis from. If we are done 'i' iterating over the string, we
12+
reverse the string and now we check for invalid parenthesis with an extra '(' and so, we call the same code recursively.
13+
once we are done, so we reverse back to original valid string and add to result. The control goes back to return statement
14+
to find the next ')' since j goes from jStart to i.
15+
The program only looks for valid answers which in this case if it is 'k', then time complexity would be O(nk) where n is
16+
the length of the string.
17+
*/
18+
819
public void removeHelper(String s, List<String> output, int iStart, int jStart, char openParen, char closedParen) {
920
int numOpenParen = 0, numClosedParen = 0;
1021
for (int i = iStart; i < s.length(); i++) {
@@ -20,9 +31,9 @@ public void removeHelper(String s, List<String> output, int iStart, int jStart,
2031
}
2132
// No invalid closed parenthesis detected. Now check opposite direction, or reverse back to original direction.
2233
String reversed = new StringBuilder(s).reverse().toString();
23-
if (openParen == '(')
34+
if (openParen == '(') // to check wheteher we have just checked for the original version of the string or reverse.
2435
removeHelper(reversed, output, 0, 0, ')','(');
2536
else
26-
output.add(reversed);
37+
output.add(reversed); // we have checked both the original and reversed version.
2738
}
2839
}

0 commit comments

Comments
 (0)