2. Valid Parentheses
easyAsked at MercadoLibreDetermine if a string of brackets is properly matched and nested.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given a string s containing only the characters '(', ')', '{', '}', '[' and ']', determine if the input string 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 of bracket characters only
Examples
Example 1
s = "()[]{}"trueExample 2
s = "(]"falseApproaches
1. Brute force
Repeatedly strip matched pairs.
- 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; on a close, pop and verify pair. Stack must be empty at the end.
- Time
- O(n)
- Space
- O(n)
function isValid(s) {
const pair = { ')':'(', ']':'[', '}':'{' };
const st = [];
for (const c of s) {
if ('([{'.includes(c)) st.push(c);
else if (st.pop() !== pair[c]) return false;
}
return st.length === 0;
}Tradeoff:
MercadoLibre-specific tips
MercadoLibre uses this to filter for stack intuition — handy for nested cart/checkout flows where each step opens state that must close cleanly.
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 MercadoLibre interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →