QuestionsDSA

Valid Parentheses

Stack / Monotonic StackEasyDSA

Given a string of '()[]{}', return true if brackets are correctly opened and closed in order.

What it tests

Recognizing LIFO nesting — the defining use case of a stack.

Approach & answer

Push opening brackets. On a closing bracket, the top of the stack must be its matching opener; if not (or stack empty), it's invalid. Valid iff the stack ends empty. Nesting = last-opened-first-closed = stack. Map closers→openers for O(1) matching. The subtle case is a leading closer like ')': the stack is empty, so `stack.pop()` returns `undefined`, which never equals a valid opener — the early `return false` catches it without a separate emptiness check. This 'match against the most recent unmatched thing' shape recurs in expression parsing, HTML/XML validation, and editor bracket-highlighting.

Use this technique when

Matching pairs, nesting, or 'undo to the most recent' → stack.

Complexity

Time O(n) · Space O(n)

References

js