Skip to main content

2. Valid Parentheses

easyAsked at CircleCI

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

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

Problem

Given a string s containing only the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if brackets close in correct order and every closing bracket has a matching opener of the same type.

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. Brute force replace

Repeatedly strip matching pairs until no change.

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

Tradeoff:

2. Stack

Push openers onto a stack; on a closer, pop and verify it matches the expected pair.

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

Tradeoff:

CircleCI-specific tips

CircleCI uses this to check that you can model a job-graph parser cleanly; favor an explicit stack over regex tricks.

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

Practice these live with InterviewChamp.AI →