2. Valid Parentheses
easyAsked at BookingUse a stack to validate matching brackets — Booking screens this to confirm you can model nested filter expressions in search.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given a string containing the characters '(', ')', '{', '}', '[', ']', determine if the input string is valid: open brackets are closed by the same type in the correct order.
Constraints
1 <= s.length <= 10^4s consists of parentheses only
Examples
Example 1
s = "()[]{}"trueExample 2
s = "(]"falseApproaches
1. Brute force replace
Repeatedly remove '()', '[]', '{}' 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 opens, pop on close and verify it matches the expected type.
- Time
- O(n)
- Space
- O(n)
function isValid(s) {
const map = { ')': '(', ']': '[', '}': '{' };
const stack = [];
for (const c of s) {
if (c in map) {
if (stack.pop() !== map[c]) return false;
} else {
stack.push(c);
}
}
return stack.length === 0;
}Tradeoff:
Booking-specific tips
Booking values clean handling of nested availability calendar expressions — connect the stack to validating nested search-filter trees.
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 Booking interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →