Skip to main content

2. Valid Parentheses

easyAsked at Etsy

Validate balanced brackets using a stack — Etsy's quick screen for whether you reach for the right data structure.

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 opener must match its closer.

Constraints

  • 1 <= s.length <= 10^4
  • s consists of brackets only

Examples

Example 1

Input
s = "()[]{}"
Output
true

Example 2

Input
s = "(]"
Output
false

Approaches

1. Brute force replace

Repeatedly strip matched pairs until no change occurs.

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, pop on closers, fail on mismatch. Empty stack at end means valid.

Time
O(n)
Space
O(n)
function isValid(s) {
  const stack = [];
  const match = { ')':'(', ']':'[', '}':'{' };
  for (const c of s) {
    if (c in match) {
      if (stack.pop() !== match[c]) return false;
    } else stack.push(c);
  }
  return stack.length === 0;
}

Tradeoff:

Etsy-specific tips

Etsy will probe whether you'd extend this to validate tag-nesting in listing descriptions — show you understand stacks scale to real marketplace HTML sanitation.

Solve it now

Free. No sign-up. Python and JavaScript run instantly in your browser.

Output

Press Run or Cmd+Enter to execute

Practice these live with InterviewChamp.AI

Drill Valid Parentheses and other Etsy interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →