Created
July 20, 2017 00:20
-
-
Save jerryvig/9d4f2f1a9ca6017975a54c8f839066c7 to your computer and use it in GitHub Desktop.
Interview Question - Remove Invalid Parentheses - JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
Interviwer asks: An expression will be given which can contain open and close parentheses and | |
optionally some characters, No other operator will be there in string. We need to remove the minimum | |
number of parentheses to make the input string valid. If more than one valid output is possible | |
removing the same number of parentheses, then print all such output possibilities. | |
*/ | |
function isValidString(s) { | |
var count = 0; | |
for (let c of s) { | |
if (c === '(') { | |
count++; | |
} | |
else if (c === ')') { | |
count--; | |
} | |
if (count < 0) return false; | |
} | |
return count === 0; | |
} | |
function removeInvalidParentheses(s) { | |
let levels = [s]; | |
while (true) { | |
let valid = levels.filter(isValidString); | |
if (valid.length > 0) { | |
return new Set(valid); | |
} | |
// check validity of all possible substrings with one character removed. | |
let nextlevels = []; | |
for (let s of levels) { | |
for (let i = 0; i < s.length; i++) { | |
nextlevels.push(s.substring(0, i) + s.substring(i + 1)); | |
} | |
} | |
levels = nextlevels; | |
} | |
} | |
console.log(removeInvalidParentheses(')()()(')); | |
console.log(removeInvalidParentheses('(()))')); | |
console.log(removeInvalidParentheses(')(')); | |
console.log(removeInvalidParentheses('()))(()')); | |
console.log(removeInvalidParentheses('(()())')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
My solutions was;