2. Valid Parentheses
easyAsked at UdemyValidate that brackets nest correctly — a stack warm-up Udemy uses to gauge whether you reach for the right data structure before the harder DRM/search rounds.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given a string containing the characters '(){}[]', determine whether the brackets are matched and properly nested. Return true if valid and false otherwise.
Constraints
1 <= s.length <= 10^4s only contains bracket characters
Examples
Example 1
s = "()[]{}"trueExample 2
s = "(]"falseApproaches
1. Brute force string replace
Repeatedly strip empty pairs until the string is unchanged.
- Time
- O(n^2)
- Space
- O(n)
let prev;
while (prev !== s) {
prev = s;
s = s.replace('()','').replace('[]','').replace('{}','');
}
return s.length === 0;Tradeoff:
2. Stack
Push openers; on a closer, the top of the stack must be its match. The string is valid iff the stack ends empty.
- Time
- O(n)
- Space
- O(n)
function isValid(s) {
const pair = { ')': '(', ']': '[', '}': '{' };
const stack = [];
for (const ch of s) {
if ('([{'.includes(ch)) stack.push(ch);
else if (stack.pop() !== pair[ch]) return false;
}
return stack.length === 0;
}Tradeoff:
Udemy-specific tips
Frame this as validating nested course curriculum structures (sections inside lessons inside courses) — Udemy interviewers like candidates who connect the stack pattern to their content tree.
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 Udemy interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →