DSA Stacks

Valid Parentheses

Push openers; on a closer, the stack top must be its match.

Easy
Time O(n) Space O(n)
LeetCode
3 min read
stack parsing

Problem#

Given a string containing only ()[]{}, return whether all brackets are correctly closed and properly nested.

Examples#

  • "()"true
  • "()[]{}"true
  • "(]"false
  • "([)]"false

Constraints#

  • 1 <= s.length <= 10^4.

Approach#

Push each opener onto a stack. For each closer, pop and compare against the expected match. At the end, the stack must be empty.

Solution#

Valid Parentheses
class Solution {
public:
bool isValid(string s) {
stack<char> st;
for (char c : s) {
if (c == '(' || c == '[' || c == '{') st.push(c);
else {
if (st.empty()) return false;
char t = st.top(); st.pop();
if ((c == ')' && t != '(') ||
(c == ']' && t != '[') ||
(c == '}' && t != '{')) return false;
}
}
return st.empty();
}
};

Editorial#

The “most recently opened bracket must match the next closer” invariant is exactly what a stack expresses. Every push pairs with at most one pop; mismatches and leftover openers both signal invalid input.

Complexity#

  • Time: O(n).
  • Space: O(n).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.