2. Valid Parentheses
easyAsked at CheggValidate balanced brackets using a stack — Chegg uses this to check stack fluency for parsing student LaTeX answers.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string 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 bracket characters
Examples
Example 1
s = "()[]{}"trueExample 2
s = "(]"falseApproaches
1. Repeated replace
Strip empty pairs until no change.
- Time
- O(n^2)
- Space
- O(n)
let prev;
do { prev = s; s = s.replace(/\(\)|\[\]|\{\}/g, ''); } while (s !== prev);
return s === '';Tradeoff:
2. Stack
Push openers; on closer verify it matches the top of the stack. Empty stack at end means valid.
- Time
- O(n)
- Space
- O(n)
function isValid(s) {
const pairs = { ')': '(', ']': '[', '}': '{' };
const stack = [];
for (const ch of s) {
if (ch in pairs) {
if (stack.pop() !== pairs[ch]) return false;
} else stack.push(ch);
}
return stack.length === 0;
}Tradeoff:
Chegg-specific tips
Chegg likes candidates who frame this as a parser warm-up because their student-answer ingestion pipeline tokenizes LaTeX and code submissions with stack-based validators.
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 Chegg interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →