Valid Parentheses

Free with account Updated Nov 19, 2026 · 4 min read
On this page

    Problem statement

    Given a string containing only the characters ( ) [ ] { }, decide whether it is valid: every opening bracket is closed by a bracket of the same type, and brackets close in the correct order. An empty string is valid.

    One of the most common warm-up questions. It's short, but it checks whether you reach for the right structure (a stack) and handle the two ways it can fail: a mismatch in the middle, and leftovers at the end. Original problem: LeetCode 20.

    Example

    Nested and side-by-side pairs are valid; a wrong type, crossed pairs or an unclosed opener make the string invalid.
    Nested and side-by-side pairs are valid; a wrong type, crossed pairs or an unclosed opener make the string invalid.
    Input:  "([{}])"
    Output: true
    Input:  "([)]"
    Output: false      # ) arrives while [ is still open

    Constraints (assumed)

    • 0 ≤ length ≤ 10,000.
    • Only the six bracket characters.

    What this question tests

    • Recognizing last opened, first closed and choosing a stack.
    • Handling both failure points: mismatch during the scan and leftovers at the end.
    • Clean code with a small lookup table instead of a chain of ifs.

    Questions to ask first

    1. Only brackets, or other characters too? (Here: only brackets. If other characters appear, skip them.)
    2. Is the empty string valid? (Here: yes.)
    3. Only one bracket type? If so, a counter is enough; with several types you need order.
    4. Return true/false, or the position of the first error? (Here: true/false.)