Skip to main content

2. Valid Parentheses

easyAsked at Baidu

Determine if a string of brackets is properly opened and closed.

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

Problem

Given a string s containing only the characters '()[]{}', determine if the input string is valid. An input is valid if open brackets are closed by the same type in the correct order.

Constraints

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

Examples

Example 1

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

Example 2

Input
s = "(]"
Output
false

Approaches

1. Brute force

Repeatedly remove matched pairs until stable.

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

Tradeoff:

2. Stack

Push opens, pop and match closes. Result must end with an empty stack.

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

Tradeoff:

Baidu-specific tips

Baidu uses this as a parser-warmup; mention how a bracket-balancing pass shows up in their query-parser for the search front-end.

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

Practice these live with InterviewChamp.AI →