How do you validate balanced parentheses?easy

Type
problem-solving
Topic
stack-valid-parentheses
Frequency
common
Tags
stack, string
Answer

Use a stack: push opening brackets and pop when a matching closing bracket appears.

Explanation

The stack stores the most recent unmatched opening bracket. If a closing bracket does not match the top of the stack, the string is invalid. At the end, the stack must be empty.

Hint: reason from constraints before calculating.
Follow-upWhy is a stack a natural fit for nested structures?