Skip to main content

2. Valid Parentheses

easyAsked at Chime

Given a string containing brackets, determine if every opening bracket is properly closed in the right order.

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

Problem

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

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 remove pair substrings until stable.

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

Tradeoff:

2. Stack

Push openings; on closing, pop and check match. Empty stack at end means valid.

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

Tradeoff:

Chime-specific tips

Chime engineers often parse webhook payloads and ACH transaction batches; demonstrate stack-based validation skills that translate to transaction-state machine validation.

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

Practice these live with InterviewChamp.AI →