2. Valid Parentheses
easyAsked at JetBrainsDetermine if a string of brackets is balanced — the bread-and-butter check inside every JetBrains parser before AST construction.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given a string containing only the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. Brackets must close in the correct order and types must match.
Constraints
1 <= s.length <= 10^4s consists of parentheses only '()[]{}'.
Examples
Example 1
s="()[]{}"trueExample 2
s="(]"falseApproaches
1. Repeated replacement
Strip empty matched pairs until stable; expensive due to repeated scans.
- Time
- O(n^2)
- Space
- O(n)
let prev;
while (prev !== s) {
prev = s;
s = s.replace('()','').replace('[]','').replace('{}','');
}
return s.length === 0;Tradeoff:
2. Stack
Push openers; on a closer, pop and verify match. Single pass linear scan mirrors how parsers track lexer brace depth.
- Time
- O(n)
- Space
- O(n)
function isValid(s) {
const pair = { ')': '(', ']': '[', '}': '{' };
const stack = [];
for (const ch of s) {
if (ch in pair) {
if (stack.pop() !== pair[ch]) return false;
} else stack.push(ch);
}
return stack.length === 0;
}Tradeoff:
JetBrains-specific tips
JetBrains expects you to frame this as the same shape as a recursive-descent parser's brace tracker — explicitly map the stack to a parser state.
Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
Practice these live with InterviewChamp.AI
Drill Valid Parentheses and other JetBrains interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →