Problem Statement
Given a string s containing just the characters (, ), {, }, [ and ], determine if the input string is valid.
Intuition
A stack naturally models the nesting structure of brackets. Every time we see an opening bracket, we push it. When we see a closing bracket, we check if it matches the top of the stack.
Approach
- Create an empty stack.
- For each character in the string:
- If it's an opening bracket, push it onto the stack.
- If it's a closing bracket, check if the stack is non-empty and the top matches. If not, return false.
- Return true if the stack is empty at the end.
Solution
TypeScript
function isValid(s: string): boolean {
const stack: string[] = [];
const pairs: Record<string, string> = {
")": "(",
"]": "[",
"}": "{",
};
for (const ch of s) {
if (ch in pairs) {
if (stack.pop() !== pairs[ch]) return false;
} else {
stack.push(ch);
}
}
return stack.length === 0;
}
Complexity Analysis
| Metric | Value | Explanation |
|---|---|---|
| Time | Single pass through the string | |
| Space | Stack stores up to n/2 opening brackets |