All coding questions

Valid Parentheses

easy
Blind 75NeetCode 150stackstrings

Problem

Given a string of bracket characters drawn from round, square, and curly pairs, decide whether every opening bracket is closed by the correct type in the correct order. Return true if the string is well balanced.

Examples

Input: s = "()[]{}"
Output: true
Each bracket closes its matching opener in order.
Input: s = "(]"
Output: false
A round opener is closed by a square bracket.

Constraints

  • 1 <= s.length <= 10^4
  • String contains only bracket characters
Hints(tap to reveal)
  • 1. A stack remembers the most recent unclosed opener.
  • 2. A closer must match the top of the stack.
Optimal approach(spoiler)
  1. Push every opening bracket onto a stack.
  2. On a closing bracket, pop and verify the popped opener matches its type.
  3. If the stack is empty when a closer arrives, it is invalid.
  4. After scanning, the stack must be empty for a valid string.
  5. O(n) time, O(n) space.

Ready to solve it?

Write your solution in the editor and get an instant AI grade on correctness, edge cases, and complexity.

Practice in the editor