Back to Practice
#0031

Valid Parentheses

EasyDSA15 min10 XP

Problem

Given a string containing only brackets, return True if every opening bracket is closed by the correct type in the correct order.

Why This Matters

This is the cleanest beginner example of why stacks exist: the last opened bracket must be the first one closed.

Function Signature

def is_valid(s):

Examples

Example 1
Inputs = "([]){}"
OutputTrue

Every closing bracket matches the most recent unmatched opening bracket.

Example 2
Inputs = "([)]"
OutputFalse

The ")" tries to close "(", but "[" is still open on top of the stack.

Constraints

  • String contains only bracket characters.
  • Empty string is valid.
CodePython
Visible browser tests run here when available.
Testcases2 visible / 4 hidden categories
Nested valid
Input"([]){}"
ExpectedTrue

Nested and adjacent groups are both handled.

Wrong order
Input"([)]"
ExpectedFalse

Correct counts are not enough; order matters.

Hidden Test Categories
Empty stringOnly opening bracketsOnly closing bracketsDeep nesting