Valid Parentheses

EasyStackFree to try
Asked byAmazonLinkedInFacebookMicrosoftBloombergSpotify

Problem

Given a string containing only the characters '(', ')', '{', '}', '[' and ']', determine whether the string is valid — every opening bracket must be closed by the same type of bracket, and brackets must close in the correct order.

Examples

Example 1
Input:s = "()[]{}"
Output:true
Example 2
Input:s = "(]"
Output:false

Constraints

  • 1 <= s.length <= 10^4

Try it now — no sign-up needed. Write your solution in Python or JavaScript, run it against test cases, and submit for a verdict, right in your browser.

Open the editor →

How to approach it: the Stack pattern

A stack is last-in-first-out — the most recently added item is the first one removed. It's the natural fit whenever "the most recent unmatched thing" matters, like nested brackets or undo history.

Look for this pattern when

  • You're validating nested or paired structures (parentheses, tags, nested expressions).
  • You need to track "the most recent X that hasn't been resolved yet."
  • You're looking for the next larger or smaller element relative to each position.

Read the full Stack guide →

Video walkthroughs

Original problem on LeetCode ↗

More Stack problems