Use a stack to validate nested brackets and parentheses.
Use the editor below to validate the order and type of every closing symbol.
Track unmatched opening symbols
Store opening symbols until their matching closing symbols arrive. Check incorrect nesting, extra opening symbols, and a closing symbol with no opener.
Submit your implementation when it passes the examples.
Given a string containing only parentheses, brackets, and braces, return true when every opening symbol is closed by the same type in the correct order.
An empty stack at the end means every opening symbol was matched.
1 ≤ s.length ≤ 10,000Results appear here after a run.
Push every opening symbol onto a stack. For a closing symbol, pop the most recent opener and verify that it is the required matching type.
In ([)], the first closing ) meets [ at the top. Return false immediately even though the numbers of opening and closing symbols agree. A closer with an empty stack also fails. After the last symbol, the stack must be empty for the string to be valid.
function isValidParentheses(s) {
const expectedOpening = new Map([
[")", "("],
["]", "["],
["}", "{"],
]);
const stack = [];
for (const symbol of s) {
if (!expectedOpening.has(symbol)) {
stack.push(symbol);
continue;
}
if (stack.pop() !== expectedOpening.get(symbol)) {
return false;
}
}
return stack.length === 0;
}| Measure | Complexity | Explanation |
|---|---|---|
| Time | O(n) | Every symbol is inspected and pushed or popped at most once. |
| Auxiliary space | O(n) | An input containing only opening symbols fills the stack. |