2. Valid Parentheses
easyAsked at SwiggyCheck whether a string of brackets is well-formed.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given a string containing only '()[]{}', determine whether the input string is valid. Brackets must close in correct order and types must match.
Constraints
1 <= s.length <= 10^4s contains only bracket characters
Examples
Example 1
Input
s="()[]{}"Output
trueExample 2
Input
s="(]"Output
falseApproaches
1. Brute force replace
Repeatedly remove '()','[]','{}' until stable; check empty.
- 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 on closers and verify match.
- Time
- O(n)
- Space
- O(n)
function isValid(s) {
const pair = { ')': '(', ']': '[', '}': '{' };
const stack = [];
for (const c of s) {
if (c === '(' || c === '[' || c === '{') stack.push(c);
else if (stack.pop() !== pair[c]) return false;
}
return stack.length === 0;
}Tradeoff:
Swiggy-specific tips
Swiggy uses this as a fluency check; mention validating order-modifier nesting (combos, add-ons) as a real production analogue.
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 Swiggy interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →