Skip to main content

2. Valid Parentheses

easyAsked at Mercury

Determine if a string of brackets is validly nested and matched.

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

Problem

Given a string s containing the characters '()[]{}', determine if the input string is valid. Open brackets must be closed by the same type of brackets and in the correct order.

Constraints

  • 1 <= s.length <= 10^4
  • s consists only of '()[]{}'

Examples

Example 1

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

Example 2

Input
s = "(]"
Output
false

Approaches

1. Repeated replace

Keep removing '()', '[]', '{}' substrings until nothing changes.

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

Tradeoff:

2. Stack of openers

Push openers, pop and match on closers; reject on mismatch or leftover. Single linear pass.

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

Tradeoff:

Mercury-specific tips

At Mercury, frame this as validating nested JSON payloads from partner bank webhooks where an unmatched delimiter must abort ledger commits before any double-write.

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

Practice these live with InterviewChamp.AI →