Blind 75 · Stack

Valid Parentheses

Easy

Watch the walkthrough (5:38)

Problem

The input is a string s made only of brackets: round, square and curly.
Each bracket either opens or closes.
Return true if every opening bracket is closed by a closing bracket of the same type.
Brackets must close in the right order.
Every closing bracket must close an opening bracket.
Otherwise, return false.

Examples

Example 1:
Input: s = "()"
Output: true

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

Example 3:
Input: s = "(]"
Output: false

Example 4:
Input: s = "([)]"
Output: false

Example 5:
Input: s = "{[]}"
Output: true

Constraints

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

Prerequisites

Stacks — last in, first out, and why that is the right shape for nesting.

How to think about it

1. Stack of Brackets Still Open

Intuition

A closing bracket must close the last bracket still open. So keep the opening brackets still open on a stack, the last one on top, and a map, closer, that gives each opening bracket its closing partner. An opening bracket goes on the stack. A closing bracket must be the top's closer: then the pair is matched, and the top comes off. If a closing bracket comes with nothing open, or the top's closer is not that bracket, the answer is false at once. At the end, the string is valid only if nothing is left open.

Algorithm

1. Keep closer, a map from each opening bracket to its closing bracket, and an empty stack.
2. Read the string a bracket at a time. An opening bracket goes on the stack.
3. A closing bracket with nothing open: return false.
4. A closing bracket that is not the top's closer: return false. Otherwise the top comes off.
5. At the end, return whether the stack is empty: anything left on it was never closed.

Time & Space

Time O(n) — each bracket goes on the stack at most once and comes off at most once. Space O(n): if every bracket opens, the stack grows to n brackets.

2. Stack of Expected Closers Optimal

Intuition

Nesting is last-in-first-out, which is the definition of a stack. Every opening bracket promises a matching closer, and the most recent promise must be kept first — so push what you expect to see, and check each closer against the top.

Algorithm

1. For an opening bracket, push its matching closer.
2. For a closing bracket, it must equal the top of the stack — otherwise the string is invalid.
3. A closer arriving on an empty stack is invalid too.
4. Valid exactly when the stack ends empty; leftovers are unclosed openers.

Time & Space

Time O(n). Space O(n) in the worst case, when every character is an opener.