Neural Mastery
← Practice
Valid Parentheseseasy

Valid Parentheses

easy Coding Interview Patterns 10–15 min

NumPy allowed · plain Python earns 10 bonus points

Implement Valid Parentheses, the canonical stack problem used verbatim in compilers, linters, and expression evaluators.

Related Skills

Task

Implement is_valid(s): push every opening bracket onto a stack. On a closing bracket, check the stack's top against a closer-to-opener map -- if it doesn't match (or the stack is empty), the string is invalid. Valid iff the stack is empty at the end.

Function Signature

is_valid(s: str) -> bool

Examples

Example 1: Simple Valid Pair
Input: s = '()'
Output: True
Example 2: Multiple Types Valid
Input: s = '()[]{}'
Output: True
Example 3: Mismatched Closer
Input: s = '(]'
Output: False

Constraints

  • Libraries are allowed; a plain-Python solution earns 10 bonus points.
  • An empty string is valid (returns True).
  • A closer with no matching opener on the stack makes the string invalid immediately.
Python3Saved ✓
def is_valid(s: str) -> bool:
"""s: a string of the characters ()[]{}. Return True if every opener
is matched by the correct closer in valid nesting order."""
# Your implementation here
pass

Case 1: Simple Valid Pair
Input: s = '()'
Expected: True
Case 2: Multiple Types Valid
Input: s = '()[]{}'
Expected: True
Case 3: Mismatched Closer
Input: s = '(]'
Expected: False