2. Valid Parentheses
easyAsked at FreshworksDetermine if a string of brackets is correctly opened and closed.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given a string containing only the characters '()[]{}', determine if it is valid. Open brackets must close in the correct order.
Constraints
1 <= s.length <= 10^4s consists of brackets only
Examples
Example 1
Input
s="()[]{}"Output
trueExample 2
Input
s="(]"Output
falseApproaches
1. Naive replace
Repeatedly remove '()', '[]', '{}'.
- Time
- O(n^2)
- Space
- O(n)
while (s.includes('()')||s.includes('[]')||s.includes('{}')) {
s = s.replace('()','').replace('[]','').replace('{}','');
}
return s==='';Tradeoff:
2. Stack
Push opens, pop and match on closes. Stack must be empty at end.
- Time
- O(n)
- Space
- O(n)
function isValid(s) {
const map = {')':'(',']':'[','}':'{'};
const st = [];
for (const c of s) {
if (c in map) {
if (st.pop() !== map[c]) return false;
} else st.push(c);
}
return st.length === 0;
}Tradeoff:
Freshworks-specific tips
Freshworks interviewers care about edge cases like empty strings and unmatched closers — name them aloud.
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 Freshworks interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →