easy +10 pts

Balanced brackets in string

Given a string of brackets, determine if every opening bracket has a matching closing bracket in the correct order.

Write a function `is_balanced(s: str) -> bool` that returns `True` if the input string `s` contains only properly matched and nested brackets `()`, `[]`, and `{}`, and `False` otherwise. A string is balanced if: - Every opening bracket has a corresponding closing bracket of the same type later in the string. - Brackets close in the correct order (e.g., `([)]` is **not** balanced). - All characters in the string are brackets; there are no other characters. Examples: - `is_balanced("")` → `True` (empty string has no brackets, so it is balanced). - `is_balanced("()[]{}``) → `True` - `is_balanced("([{}])")` → `True` - `is_balanced("(]")` → `False` - `is_balanced("([)]")` → `False` - `is_balanced("{")` → `False`

Constraints

- Input `s` is a string containing only the characters `()[]{}`. - Length of `s` is between 0 and 10^5. - Time complexity should be O(n), space complexity O(n).

Example

>>> is_balanced("()[]{}")
True
>>> is_balanced("([{}])")
True
>>> is_balanced("(]")
False
>>> is_balanced("([)]")
False
>>> is_balanced("")
True
10 points ~15 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Use a stack: push opening brackets, pop on closing bracket.
When you see a closing bracket, the top of the stack must match.
At the end, the stack must be empty.
Handle the empty string correctly.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.