Check if a string containing only parentheses ()[]{} is valid.
A string is valid if:
- Open brackets are closed by the same type of brackets
- Open brackets are closed in the correct order
Solution using Stack
function isValidParentheses(s) {
const stack = [];
const map = {
"(": ")",
"{": "}",
"[": "]"
};
for (let char of s) {
if (map[char]) {
// If it's an opening bracket, push the expected closing bracket
stack.push(map[char]);
} else {
// If it's a closing bracket, it must match the top of the stack
if (stack.pop() !== char) {
return false;
}
}
}
// Stack should be empty if all brackets are matched
return stack.length === 0;
}
// Example usage
console.log(isValidParentheses("()")); // true
console.log(isValidParentheses("()[]{}")); // true
console.log(isValidParentheses("(]")); // false
console.log(isValidParentheses("([{}])")); // true
console.log(isValidParentheses("(((")); // false
Explanation:
- Stack Approach:
- Push expected closing brackets when encountering an opening bracket.
- When encountering a closing bracket, check if it matches the top of the stack.
- Validation:
- If the stack is empty at the end → all brackets matched.
- If not → invalid parentheses.
- Time Complexity:
- O(n), where n = length of the string
- Space Complexity:
- O(n) for the stack
⚡ In short:
Use a stack to track expected closing brackets; validate each closing bracket against the stack. If the stack is empty at the end, the parentheses are valid.