import re
def remove_parentheses(s):
s = s.replace('()', '') # Bonus!
opens = [m.start() for m in re.finditer(r'\(', s)]
closes = [m.start() for m in re.finditer(r'\)', s)]
pairs = []
while opens:
open = opens.pop()
close = [c for c in closes if c > open][0]
closes.remove(close)
pairs.append((open, close))
nested = sorted([(a, b) for a, b in pairs if (a + 1, b - 1) in pairs])
while nested:
open, close = nested.pop()
s = s[:open] + s[open + 1:close] + s[close + 1:]
nested = [(a, b if b < close else b - 2) for a, b in nested]
return s or 'NULL'
print(remove_parentheses('((a((bc)(de)))f)'))
print(remove_parentheses('(((zbcd)(((e)fg))))'))
print(remove_parentheses('ab((c))'))
print(remove_parentheses('()'))
print(remove_parentheses('((fgh()()()))'))
print(remove_parentheses('()(abc())'))
aW1wb3J0IHJlCgpkZWYgcmVtb3ZlX3BhcmVudGhlc2VzKHMpOgogICAgcyA9IHMucmVwbGFjZSgnKCknLCAnJykgICMgQm9udXMhCiAgICBvcGVucyA9IFttLnN0YXJ0KCkgZm9yIG0gaW4gcmUuZmluZGl0ZXIocidcKCcsIHMpXQogICAgY2xvc2VzID0gW20uc3RhcnQoKSBmb3IgbSBpbiByZS5maW5kaXRlcihyJ1wpJywgcyldCiAgICBwYWlycyA9IFtdCiAgICB3aGlsZSBvcGVuczoKICAgICAgICBvcGVuID0gb3BlbnMucG9wKCkKICAgICAgICBjbG9zZSA9IFtjIGZvciBjIGluIGNsb3NlcyBpZiBjID4gb3Blbl1bMF0KICAgICAgICBjbG9zZXMucmVtb3ZlKGNsb3NlKQogICAgICAgIHBhaXJzLmFwcGVuZCgob3BlbiwgY2xvc2UpKQogICAgbmVzdGVkID0gc29ydGVkKFsoYSwgYikgZm9yIGEsIGIgaW4gcGFpcnMgaWYgKGEgKyAxLCBiIC0gMSkgaW4gcGFpcnNdKQogICAgd2hpbGUgbmVzdGVkOgogICAgICAgIG9wZW4sIGNsb3NlID0gbmVzdGVkLnBvcCgpCiAgICAgICAgcyA9IHNbOm9wZW5dICsgc1tvcGVuICsg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