InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Stack

Valid Parentheses

easy Original ↗ 00:00

Problem

You get a string made up only of the six bracket characters: (, ), {, }, [, ]. Decide whether the string is balanced: every opening bracket must be closed by a closing bracket of the same type, and brackets must close in the reverse order they were opened (the most recently opened bracket is always the first one closed). An empty stack of unfinished brackets at the end means the string is valid.

Return True if the string is balanced, False otherwise.

Examples

  • "()[]{}"True — three independent pairs, each opened and immediately closed.
  • "([{}])"True — pairs nest properly: the innermost {} closes first, then [], then ().
  • "(]"False — the closer ] does not match the most recent opener (.
  • "(("False — two openers are never closed.

Constraints

  • 1 <= s.length <= 10^4
  • s consists only of the characters ()[]{}

The length bound makes a repeated-rescanning O(n^2) solution slow; the expected solution is a single O(n) pass.

Think about it first

Hint 1 Think about what makes `"(]"` invalid: when you reach a closing bracket, only one specific opener is allowed to be "waiting" for it. Which one?
Hint 2 The bracket that was opened most recently must be the first one to close. "Most recent thing first" is exactly what a LIFO structure — a stack — gives you in O(1).
Hint 3 Scan left to right. Push every opener. On a closer, pop the stack and check that the popped opener is the matching type (fail if the stack is empty or the types differ). The string is valid iff you never fail and the stack is empty at the end.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug