2. Valid Parentheses
easyAsked at ExpediaDetermine if a string of brackets is properly opened and closed in the right order.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string 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. Brute force replacement
Repeatedly remove matched pairs until no more remain.
- 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 on close and verify match. Expedia uses similar logic when validating nested itinerary payloads from suppliers.
- Time
- O(n)
- Space
- O(n)
function isValid(s) {
const stack = [];
const pairs = { ')': '(', ']': '[', '}': '{' };
for (const c of s) {
if (c in pairs) {
if (stack.pop() !== pairs[c]) return false;
} else stack.push(c);
}
return stack.length === 0;
}Tradeoff:
Expedia-specific tips
Expedia interviewers care about edge cases like empty strings and unbalanced inputs, since supplier itinerary parsers must handle malformed XML/JSON gracefully.
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 Expedia interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →