Skip to main content

2. Valid Parentheses

easyAsked at Squarespace

Validate that brackets in a string are balanced; Squarespace screens use it to test stack reasoning relevant to nested template blocks.

By Alex Chen, Founder, InterviewChamp.AI · Last verified

Problem

Given a string s containing only the characters '()[]{}', determine if every opener is closed by the matching type in the right order.

Constraints

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

Examples

Example 1

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

Example 2

Input
s="(]"
Output
false

Approaches

1. Repeated replace

Strip matched pairs until stable.

Time
O(n^2)
Space
O(n)
let p=s; while (/\(\)|\[\]|\{\}/.test(p)) p=p.replace(/\(\)|\[\]|\{\}/g,''); return p===''

Tradeoff:

2. Stack

Push openers, pop on close and compare to the expected match.

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

Tradeoff:

Squarespace-specific tips

Squarespace cares that you mention how the same stack approach validates their Liquid-style template tags before publish.

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 Squarespace interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →