2. Valid Parentheses
easyAsked at GrabValidate matched brackets using a stack — a Grab classic for testing data-structure intuition.
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. Brackets must close in the correct order and each opening bracket must have a matching close.
Constraints
1 <= s.length <= 10^4s consists of parentheses only
Examples
Example 1
s = '()[]{}'trueExample 2
s = '(]'falseApproaches
1. Brute force replace
Repeatedly remove matched pairs until nothing changes.
- 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 compare. Mismatches or leftover opens mean invalid.
- Time
- O(n)
- Space
- O(n)
function isValid(s) {
const pairs = { ')': '(', ']': '[', '}': '{' };
const stack = [];
for (const ch of s) {
if (!(ch in pairs)) stack.push(ch);
else if (stack.pop() !== pairs[ch]) return false;
}
return stack.length === 0;
}Tradeoff:
Grab-specific tips
Grab interviewers like candidates who frame this as validating nested JSON in a GrabPay receipt — concrete framing earns bonus signal.
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 Grab interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →