Skip to main content

2. Valid Parentheses

easyAsked at Quora

Determine if a string of brackets is balanced and properly nested.

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

Problem

Given a string s containing just '()[]{}', determine if the input string is valid. Brackets must be closed in the correct order and every opener has a matching closer of the same type.

Constraints

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

Examples

Example 1

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

Example 2

Input
s = "(]"
Output
false

Approaches

1. Replace pairs

Repeatedly strip empty pairs until stable.

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

Tradeoff:

2. Stack

Push openers, pop and match on closers.

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

Tradeoff:

Quora-specific tips

Quora uses stacks-as-validator questions to see if you can sanity-check nested markdown and embed tags before they hit their answer renderer.

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

Practice these live with InterviewChamp.AI →