LeetCode: Minimum Remove To Make Valid Parentheses Solution

1/**
2 * @param {string} s
3 * @return {string}
4 */
5var minRemoveToMakeValid = function (s) {
6 const parens = s
7 .split("")
8 .map((el, i) => [el, i])
9 .filter(el => "()".includes(el[0]))
10
11 const stack = []
12 for (const paren of parens) {
13 if (stack.length === 0) {
14 stack.push(paren)
15 continue
16 }
17 if (paren[0] === ")" && stack[stack.length - 1][0] == "(") {
18 stack.pop()
19 continue
20 }
21 stack.push(paren)
22 }
23
24 const set = new Set(stack.map(([, i]) => i))
25 return s
26 .split("")
27 .map((el, i) => (set.has(i) ? "" : el))
28 .join("")
29}

Comments

Loading comments...

Tags

leetcode

string

stack

Apply and earn a $2,500 bonus once you're hired on your first job!

Clients from the Fortune 500 to Silicon Valley startups

Choose your own rate, get paid on time

From hourly, part-time, to full-time positions

Flexible remote working environment

A lot of open JavaScript jobs!!

Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.

Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.

Next Post

LeetCode: Longest Nice Substring

Feb 20, 2021

Previous Post

HoningJS

Search Posts