2. Valid Parentheses
easyAsked at InstacartValidate that brackets close in the correct order — Instacart uses this as a stack-discipline check before more involved order-state validation problems.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given a string containing only '()[]{}', determine if the input is valid. An input is valid if open brackets are closed by the same type in the correct order.
Constraints
1 <= s.length <= 10^4s consists only of '()[]{}'
Examples
Example 1
s = "()[]{}"trueExample 2
s = "(]"falseApproaches
1. Brute force replace
Repeatedly strip empty pairs until nothing changes.
- Time
- O(n^2)
- Space
- O(n)
let prev = '';
while (prev !== s) {
prev = s;
s = s.replace('()', '').replace('[]', '').replace('{}', '');
}
return s.length === 0;Tradeoff:
2. Stack
Push openers, pop and match closers against the top of the stack.
- Time
- O(n)
- Space
- O(n)
function isValid(s) {
const pair = { ')': '(', ']': '[', '}': '{' };
const stack = [];
for (const c of s) {
if (!pair[c]) stack.push(c);
else if (stack.pop() !== pair[c]) return false;
}
return stack.length === 0;
}Tradeoff:
Instacart-specific tips
Instacart often pivots this into 'validate a shopper bagging sequence' — be ready to extend the stack to handle multi-bag aisle constraints.
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 Instacart interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →