Skip to content

Commit 138aeb4

Browse files
committed
Minimum Remove To Make Valid Parentheses
1 parent d50b301 commit 138aeb4

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
/**
2+
* @param {string} s Input string containing letters and parentheses.
3+
* @return {string} Possible solution to make string valid
4+
* @summary Minimum Remove to Make Valid Parentheses {@link https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/}
5+
* @description Given a string containing letters and parentheses, return valid string by removing minimum possible parentheses.
6+
* Space O(1) - using 3 arrays, each of them can have up to n elements.
7+
* Time O(n) - where n is input length.
8+
*/
9+
const minRemoveToMakeValid = s => {
10+
const stack = [];
11+
const toRemove = [];
12+
const length = s.length;
13+
14+
for (let i = 0; i < length; i++) {
15+
const char = s[i];
16+
17+
if (s[i] === ')') {
18+
if (!stack.length) toRemove.push(i);
19+
else stack.pop();
20+
}
21+
if (s[i] === '(') {
22+
stack.push(i);
23+
}
24+
}
25+
26+
const solution = [];
27+
for (let i = 0; i < length; i++) {
28+
if (!stack.includes(i) && !toRemove.includes(i)) solution.push(s[i]);
29+
}
30+
31+
return solution.join('');
32+
};

0 commit comments

Comments
 (0)