2. Valid Parentheses
easyAsked at YelpVerify a string of brackets is well-formed using a stack — Yelp uses this to test the same nesting validation it runs on user-submitted query strings for advanced search filters.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given a string containing the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input is valid if open brackets are closed by the same type and in the correct order.
Constraints
1 <= s.length <= 10^4s consists of parentheses only
Examples
Example 1
s = '()[]{}'trueExample 2
s = '(]'falseApproaches
1. Repeated replace
Repeatedly strip empty pairs until none left.
- Time
- O(n^2)
- Space
- O(n)
while (s.includes('()') || s.includes('[]') || s.includes('{}')) {
s = s.replace('()', '').replace('[]', '').replace('{}', '');
}
return s.length === 0;Tradeoff:
2. Stack
Push openers, pop and match on closers.
- Time
- O(n)
- Space
- O(n)
function isValid(s) {
const pairs = { ')': '(', ']': '[', '}': '{' };
const stack = [];
for (const c of s) {
if (!(c in pairs)) stack.push(c);
else if (stack.pop() !== pairs[c]) return false;
}
return stack.length === 0;
}Tradeoff:
Yelp-specific tips
Yelp grades cleanliness of the stack-popping loop and will follow up by asking how you'd validate a deeply nested business-filter query string before passing it to their search service.
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 Yelp interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →