Skip to content

Instantly share code, notes, and snippets.

@h2rashee
Created February 25, 2020 18:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save h2rashee/566e0d744d3248fa3efcc1cda257b5b5 to your computer and use it in GitHub Desktop.
Save h2rashee/566e0d744d3248fa3efcc1cda257b5b5 to your computer and use it in GitHub Desktop.
Given a string with parantheses, return the number of parantheses needed to ensure there are enough matching.
# (()) -> 0
# ))(( -> 4
# ()() -> 0
# (())) -> 1
# ()())( -> 2
def find_num_missing_parans(inp):
i = 0
j = 1
res = 0
# A single character string implies a paranthesis is orphaned
if len(inp) <= 1:
return 1
while i < len(inp):
if inp[i] == ')':
res = res + 1
i = i + 1
j = i + 1
continue
next = None
while j < len(inp):
if inp[j] == ')':
if next is None:
# If we haven't seen any open parans,
# we advance both pointers ahead
i = j + 1
j = j + 2
else:
# Otherwise we track both pointers forward appropriately
i = next
j = j + 1
break
# Record the next open paran we need to match if we see it
if next is None:
next = j
j = j + 1
# When there are no closing parantheses anymore,
# we stop trying to match
if j >= len(inp):
break
orphaned_parans = 0
# If we haven't looked at all the parans yet, each one left is missing a counterpart
if i < len(inp):
orphaned_parans = j-i
return res + orphaned_parans
assert find_num_missing_parans('(())') == 0
assert find_num_missing_parans('))((') == 4
assert find_num_missing_parans('()()') == 0
assert find_num_missing_parans('(()))') == 1
assert find_num_missing_parans('()())(') == 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment