Skip to content

Instantly share code, notes, and snippets.

@jerryvig
Last active July 20, 2017 00:20
Show Gist options
  • Save jerryvig/38e4a143a86ffb52c087742c11f16a53 to your computer and use it in GitHub Desktop.
Save jerryvig/38e4a143a86ffb52c087742c11f16a53 to your computer and use it in GitHub Desktop.
Interview Question - Remove Invalid Parentheses
# 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.
def isvalid(s):
ctr = 0
for c in s:
if c == '(':
ctr += 1
elif c == ')':
ctr -= 1
if ctr < 0:
return False
return ctr == 0
def removeInvalidParentheses(s):
level = set([s])
while True:
valid = list(filter(isvalid, level))
if valid:
return valid
# check validity of all possible substrings with one character removed.
nextlevels = set()
for s in level:
for i in range(len(s)):
nextlevels.add(s[:i] + s[i+1:])
level = nextlevels
# Here are some test cases.
# test_string = ')()()('
# test_string = '(()))'
# test_string = ')('
# test_string = '()))(()'
# test_string = '(()())'
print(removeInvalidParentheses(')()()('))
print(removeInvalidParentheses('(()))'))
print(removeInvalidParentheses(')('))
print(removeInvalidParentheses('()))(()'))
print(removeInvalidParentheses('(()())'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment