2. Valid Parentheses
easyAsked at KlarnaDetermine if a string of brackets is balanced and properly nested.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given a string s containing only the characters '()[]{}', determine if the input string is valid. A string is valid if open brackets are closed by the same type and in the correct order.
Constraints
1 <= s.length <= 10^4s consists only of bracket characters.
Examples
Example 1
s = "()[]{}"trueExample 2
s = "(]"falseApproaches
1. Brute force replace
Repeatedly remove 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 openers; on a closer, pop and compare. Empty stack at end means valid.
- Time
- O(n)
- Space
- O(n)
function isValid(s) {
const stack = [];
const pairs = { ')': '(', ']': '[', '}': '{' };
for (const c of s) {
if (c in pairs) {
if (stack.pop() !== pairs[c]) return false;
} else {
stack.push(c);
}
}
return stack.length === 0;
}Tradeoff:
Klarna-specific tips
Klarna engineers care about stack discipline since their installment plan parsers and risk-rule DSLs depend on balanced expression validation.
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 Klarna interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →