2. Valid Parentheses
easyAsked at WiseValidate that a string of brackets is balanced — a classic stack warm-up before Wise drills you on ledger entries that must balance debits and credits.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given a string s containing the characters '()[]{}', determine if the input string is valid. Brackets must close in the correct order and every opener has a matching closer.
Constraints
1 <= s.length <= 10^4s consists of parentheses only
Examples
Example 1
s="()[]{}"trueExample 2
s="(]"falseApproaches
1. Brute force
Repeatedly remove matching pairs until no change.
- 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 and match on closers. Linear and clean.
- Time
- O(n)
- Space
- O(n)
function isValid(s){
const stack=[]; const m={')':'(',']':'[','}':'{'};
for (const c of s){
if (c in m){ if (stack.pop()!==m[c]) return false; }
else stack.push(c);
}
return stack.length===0;
}Tradeoff:
Wise-specific tips
Wise interviewers will probe whether you can map this to ledger-pair invariants — every credit needs a matching debit, just like every opener needs a closer.
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 Wise interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →