DSA Tracker

Easy

Valid Parentheses

An easy Stack problem included in Apna College, Love Babbar 450, Striver A2Z. Below: the roles whose interviews prioritise this topic, and how to practise it.

Topic
Stack
Sheets
3
Core for
8 roles
Platform
LeetCode

The problem

Given a string containing only parentheses, curly brackets, and square brackets, determine if the input string is valid. Brackets must close in the correct order, match their corresponding open bracket types, and every closing bracket must have an open counterpart.

Example 1

Input
s = "()[]{}"
Output
true
Why
Every opened bracket is immediately closed by its matching type in the correct order.

Example 2

Input
s = "(]"
Output
false
Why
The round opening bracket is closed by a square bracket, which violates type matching.

Example 3

Input
s = "([)]"
Output
false
Why
The square bracket closes before the round bracket finishes its scope, violating nesting order.

Constraints

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

How to think about it

Updated 2026-09-09

Every closing bracket can only match the most recently opened, unmatched opening bracket. Inner scopes must resolve completely before outer scopes can close. Because the most recent bracket entered is the earliest bracket required to leave, the structure mirrors a last-in first-out sequence where opening brackets wait on a stack.

Approaches, worst first

  1. Iterative substring replacement

    time O(n^2) · space O(n)

    Continuously search for and erase adjacent matching pairs '()', '[]', and '{}' from the string until no pairs remain. If the final string is empty, the brackets balanced properly. Repeated string allocations and scans make this approach incur quadratic runtime.

  2. LIFO bracket stackWrite this one

    time O(n) · space O(n)

    Iterate through characters one by one. Push opening brackets onto a stack. When encountering a closing bracket, verify that the stack is non-empty and that its top element corresponds to the matching open type, then pop it. The string is valid if and only if the stack finishes empty after processing all characters.

Where people lose marks · 3
  • Encountering a closing bracket when the stack is empty triggers an underflow; attempting to inspect the top without checking emptiness causes a runtime exception.
  • Strings with odd total lengths can never form balanced pairs and should return false immediately.
  • Leaving remaining opening brackets on the stack after reading all characters: a string like '(((' has no mismatched closing brackets, yet fails validity because the stack is not empty.

Full solution

LIFO bracket stack: push open brackets, and on a closing bracket check the stack top matches before popping — the only approach that stays O(n) instead of the quadratic substring-erasure alternative.

Python
def is_valid(s: str) -> bool:
    pairs = {')': '(', ']': '[', '}': '{'}
    stack = []
    for ch in s:
        if ch in pairs:
            if not stack or stack.pop() != pairs[ch]:
                return False
        else:
            stack.append(ch)
    return not stack
JavaScript
function isValid(s) {
  const pairs = { ")": "(", "]": "[", "}": "{" };
  const stack = [];
  for (const ch of s) {
    if (ch in pairs) {
      if (stack.pop() !== pairs[ch]) return false;
    } else {
      stack.push(ch);
    }
  }
  return stack.length === 0;
}
Try it in the editor

The theory behind it

Stack — the ground this problem stands on. All Stack problems

What Stack is

A stack is a vertical pile of cafeteria trays where items enter and depart from one single opening at the top. The most recent item set down is the first one retrieved, while items deposited earlier remain buried underneath until newer arrivals are lifted away. This strict last-in, first-out sequence guarantees that older context stays preserved until all newer nested actions run to completion.

When to reach for it

Reach for a stack whenever an algorithm encounters nested structures like matched brackets, tags, or algebraic formulas. Problems demanding undo operations, function execution histories, or evaluating postfix arithmetic require this discipline. It is also the primary structure for monotonic queries where a task asks for the nearest greater or smaller value adjacent to each position in a series.

How the pattern works

Picture peeling layers back in exact reverse order of their arrival. Push items as pending jobs or unclosed delimiters encounter the scan. When closing boundaries appear, pop the topmost entry and check for compatibility. For monotonic patterns, maintain an invariant where elements on the stack remain strictly increasing or decreasing; pop any items that violate this rule before recording candidate answers and pushing the current item.

What each operation costs

OperationTime
push item onto the topO(1)
pop item from the topO(1)
inspect the topmost elementO(1)
What usually goes wrong with Stack
  • Popping from or peeking into an empty stack without first verifying that the size is positive, causing runtime null pointer or empty collection errors.
  • Forgetting to verify that the stack is completely empty at the end of bracket matching, which mistakenly accepts strings with dangling unclosed opening symbols.
  • Storing values instead of indices in monotonic stacks, making it impossible to calculate distance intervals between matching elements afterwards.

Which roles need this problem

Stack is a core topic for these 8 roles — if you're targeting one of them, this problem is early in your path, not optional.

Secondary for 9 more roles, including Frontend Engineer, Data Engineer, Game Developer.

Track this in your role's order

Pick your target role and all 370 problems — including this one — resequence to what that interview actually asks. Free.

Start free

More Stack problems

Problem set and role mapping as of .