STACK › PARENTHESES PROBLEM
Open — the attempt gate is not wired up yet
This editorial is meant to unlock after you have run the problem at least once, with the worked solution behind one further deliberate click. That needs per-learner unlock state nothing stores today, so for now the whole article is open.
Try it yourself first →A closing bracket cannot match just any earlier opening bracket. It must match the most recently opened bracket that has not been closed yet. For example, in ([ ]), the square bracket closes before the parenthesis because it was opened later. A stack stores exactly that unfinished nesting order: every new opening bracket goes on top, and only the top can be removed.
When a closing bracket arrives, compare it with the stack top. An empty stack means there is nothing to close, and a different bracket means the nesting order is broken; either case makes the string invalid immediately. If the types match, pop the opening bracket. At the end, the stack must be empty, because leftover openings are also unmatched.
| MEASURE | BOUND | WHY |
|---|---|---|
| Time | O(n) | The scan examines each character once. Each character causes at most one mapping lookup and one stack operation, and no character is revisited, so the total work is linear. |
| Space | O(n) extra | The returned value is a boolean and adds no output storage. The stack can hold every character in the worst input shape, such as a string containing only opening brackets, so the working memory is O(n). |
#include <stack>
#include <string>
#include <unordered_map>
using namespace std;
class Solution {
public:
bool isValid(string s) {
unordered_map<char, char> pairs = {{')', '('}, {'}', '{'}, {']', '['}};
stack<char> st;
for (char c : s) {
if (pairs.count(c)) {
if (st.empty() || st.top() != pairs[c]) {
return false;
}
st.pop();
} else {
st.push(c);
}
}
return st.empty();
}
};The condition st.empty() must be checked before st.top(), because an input beginning with a closing bracket has no element to inspect. The final st.empty() is a separate requirement: a string such as ( contains no bad closing bracket, but it still leaves an opening bracket unmatched. Together, these checks cover both directions of imbalance.