Skip to main content

2. Valid Parentheses

easyAsked at Activision

Decide whether a string of brackets is balanced — Activision uses it to gauge stack fluency relevant to chat command parsing and config validation.

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

Problem

Given a string containing the characters '(', ')', '{', '}', '[', ']', determine if the input string is valid. Brackets must close in the correct order and types must match.

Constraints

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

Examples

Example 1

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

Example 2

Input
s="(]"
Output
false

Approaches

1. Repeated replacement

Repeatedly strip matched empty pairs until no change.

Time
O(n^2)
Space
O(n)
let prev; do { prev = s; s = s.replace('()','').replace('[]','').replace('{}',''); } while (s !== prev);
return s.length === 0;

Tradeoff:

2. Stack

Push opens; on close pop and verify match. Empty stack at end = valid.

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

Tradeoff:

Activision-specific tips

Activision interviewers reward you for naming the stack-as-recursion-without-overflow insight — it foreshadows how they think about server-side validation of chat and macro inputs.

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

Practice these live with InterviewChamp.AI →