Balanced Parentheses Early Fail
Python
Hard
3 views
Problem Description
Read a string of only '(' and ')', check if it is balanced. Output YES or NO. Stop early if you ever go negative balance.
Input Format
One string s.
Official Solution
import sys
s=sys.stdin.read().strip()
if not s: sys.exit(0)
bal=0
ok=True
for ch in s:
if ch=='(':
bal+=1
else:
bal-=1
if bal<0:
ok=False
break
if ok and bal==0:
sys.stdout.write('YES')
else:
sys.stdout.write('NO')
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!