← DSA
EASY

Valid Parentheses

PracticeNeetCode ↗LeetCode ↗

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

Example

Input s = "()[]{}"
Output true

Key Pointers

Step-by-Step Analysis

  1. Create an empty stack and a mapping from each closing bracket to its matching opening bracket.
  2. For each character: if it's an opening bracket, push it onto the stack.
  3. If it's a closing bracket, check the stack isn't empty and its top matches the expected opening bracket — pop if so, otherwise return False immediately.
  4. After processing every character, return True only if the stack is empty.

Complexity

Time: O(n) — Space: O(n)

Code

def isValid(s: str) -> bool:
    pairs = {")": "(", "]": "[", "}": "{"}
    stack = []

    for ch in s:
        if ch in pairs:
            if not stack or stack[-1] != pairs[ch]:
                return False
            stack.pop()
        else:
            stack.append(ch)

    return not stack

Code Explanation

How the solution above works, piece by piece.

  1. pairs maps each closing bracket to the opening bracket it needs.
  2. An opening bracket is pushed: it waits for its partner.
  3. A closing bracket must match the most recent unmatched opener, which is exactly the top of the stack. If the stack is empty or the top is the wrong type, the string is invalid.
  4. On a match, pop the opener; that pair is done.
  5. return not stack: leftover openers were never closed. One pass: O(n) time and O(n) stack space.

Visual Walkthrough

Running it on s = "()[]{}":

Stack after each character of ()[]{}((push)emptypop match[[push]emptypop match{{push}emptypop match
Openers are pushed; each closer must match the opener on top of the stack, which is popped. The stack ends empty, so the string is valid.
pushed openermatched closer

Video Explanation

NeetCode — Valid Parentheses, LeetCode 20