Balanced Parentheses Check
MediumPractice library · +20 XPrecursionstringsparsing
Given a string consisting only of '(' and ')', determine if the parentheses are balanced. A string of parentheses is considered balanced if:
- It is empty.
- It can be written as AB, where A and B are balanced strings.
- It can be written as (A), where A is a balanced string.
Print 'YES' if the string is balanced, and 'NO' otherwise.
Input
A single line containing a string S of '(' and ')' characters.
Output
Print 'YES' or 'NO'.
Constraints
1 <= |S| <= 200000, where |S| is the length of the string.
Time limit 1 s (native code; slower languages get more)Memory 256 MB15 hidden tests
Example 1
Input
(()())
Output
YES
A valid, balanced string.
Example 2
Input
())
Output
NO
An invalid string; a closing parenthesis appears before its matching opening one.
Hints
# Read the input from stdin and print the answer.
import sys
def main():
data = sys.stdin.read().split()
# your code here
main()
Example 1 input
(()())
Example 2 input
())