2. Valid Parentheses
easyAsked at SlackGiven a string of brackets, decide whether they are balanced.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given a string s containing the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input is valid if open brackets are closed by the same type of brackets in the correct order.
Constraints
1 <= s.length <= 10^4s consists only of brackets
Examples
Example 1
s = "()[]{}"trueExample 2
s = "(]"falseApproaches
1. Brute force
Repeatedly remove matched pairs until stable.
- 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 and verify on closes. Empty stack at the end means balanced.
- Time
- O(n)
- Space
- O(n)
function isValid(s) {
const stack = [];
const map = { ')':'(', ']':'[', '}':'{' };
for (const c of s) {
if (!map[c]) stack.push(c);
else if (stack.pop() !== map[c]) return false;
}
return stack.length === 0;
}Tradeoff:
Slack-specific tips
Slack reuses bracket-matching logic in message formatting (mrkdwn) — expect a follow-up about parsing Slack's *bold* / `code` / >quote markers.
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 Slack interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →