2. Valid Parentheses
easyAsked at DuolingoDetermine if an input string of brackets is correctly opened and closed.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given a string containing only the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. Brackets must close in the correct order and every opening bracket has a matching closer of the same type.
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 '()', '[]', '{}' until no change; valid iff string is empty.
- Time
- O(n^2)
- Space
- O(n)
let prev;
do { prev = s; s = s.replace(/\(\)|\[\]|\{\}/g, ''); } while (s !== prev);
return s.length === 0;Tradeoff:
2. Stack
Push each opener; on a closer pop and verify it matches. Empty stack at end means balanced.
- Time
- O(n)
- Space
- O(n)
function isValid(s) {
const pairs = { ')': '(', ']': '[', '}': '{' };
const stack = [];
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:
Duolingo-specific tips
Duolingo lesson-tree validation runs on similar nested structures, so highlight how a stack maps cleanly to a balanced-skill-DAG check.
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 Duolingo interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →