2. Valid Parentheses
easyAsked at RampDetermine if a string of brackets is valid (every open has a matching close in the right order).
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given a string of characters '()[]{}', return true if every opening bracket has a corresponding closing bracket in the correct order and nesting.
Constraints
1 <= s.length <= 10^4s consists only of '()[]{}'
Examples
Example 1
s = "()[]{}"trueExample 2
s = "(]"falseApproaches
1. Replace pairs (brute)
Repeatedly remove matching empty pairs until stable, then check empty.
- Time
- O(n^2)
- Space
- O(n)
while (s.includes('()')||s.includes('[]')||s.includes('{}')) s = s.replace(/\(\)|\[\]|\{\}/g,'');
return s.length===0;Tradeoff:
2. Stack
Push opens, pop and verify on closes; valid iff stack empty at end. Linear time, single pass.
- Time
- O(n)
- Space
- O(n)
function isValid(s) {
const pairs = { ')': '(', ']': '[', '}': '{' };
const stack = [];
for (const ch of s) {
if (ch in pairs) {
if (stack.pop() !== pairs[ch]) return false;
} else {
stack.push(ch);
}
}
return stack.length === 0;
}Tradeoff:
Ramp-specific tips
Ramp uses bracket-matching as a warmup before pivoting into validating nested approval-policy DSL expressions, so structure your stack solution to be easily extended to typed tokens.
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 Ramp interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →