LeetCode: Minimum Add to Make Parentheses Valid Solution
Maintain balance, and yes, also naming variablesApproach: Maintain balance
If it is an open (
then we need a close, so needClose++
If it is a close )
- if close are in need, satisfy it,
needClose--
- if there is no close in need at the moment, then we need a open,
needOpen++
The result is the sum of both in need
Implementation
1var minAddToMakeValid = function (s) {2 let needOpen = 03 let needClose = 045 for (const char of s) {6 if (char === "(") {7 needClose++8 }910 if (char === ")") {11 if (needClose > 0) {12 needClose--13 } else {14 needOpen++15 }16 }17 }1819 return needOpen + needClose20}
Approach: Stack
Keep adding to stack
Popout ()
pairs during the process
The amount of what are need is the stack leftover
Implementation
1var minAddToMakeValid = function (s) {2 const stack = []34 for (const char of s) {5 if (char === "(") {6 stack.push(char)7 }89 if (char === ")") {10 if (stack.slice(-1)[0] === "(") {11 stack.pop()12 } else {13 stack.push(char)14 }15 }16 }1718 return stack.length19}
References
Similar problems
Minimum Number of Swaps to Make the String Balanced
Comments
Loading comments...
Tags
leetcode
string
greedy
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
Modified version of Longest Common Subsequence problem
Previous Post
Backtracking with duplication check