2. Valid Parentheses
easyAsked at LINEValidate a string of brackets — LINE uses it to check whether you reach for a stack instantly when a chat message body has nested formatting.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given a string containing only '()[]{}', determine if the input is valid. Brackets must close in the correct order and every opening bracket must have a matching closing bracket of the same type.
Constraints
1 <= s.length <= 10^4s consists of parentheses only.
Examples
Example 1
s = "()[]{}"trueExample 2
s = "(]"falseApproaches
1. Replace pairs in a loop
Keep collapsing '()', '[]', '{}' until the string is empty or no change happens.
- Time
- O(n^2)
- Space
- O(n)
while (/\(\)|\[\]|\{\}/.test(s)) s = s.replace(/\(\)|\[\]|\{\}/g,'');
return s.length===0;Tradeoff:
2. Stack
Push openers, pop and compare on closers, and require an empty stack at the end.
- Time
- O(n)
- Space
- O(n)
function isValid(s) {
const pair = { ')': '(', ']': '[', '}': '{' };
const stack = [];
for (const c of s) {
if ('([{'.includes(c)) stack.push(c);
else if (stack.pop() !== pair[c]) return false;
}
return stack.length === 0;
}Tradeoff:
LINE-specific tips
LINE interviewers like when you tie this to validating user-submitted rich-text markup in a chat bubble before render — show product instinct, not just leetcode.
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 LINE interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →