Skip to main content

2. Valid Parentheses

easyAsked at Adyen

Given a string of brackets, determine if every opener has a matching, properly nested closer.

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

Problem

Given a string s containing only '()[]{}', determine if every opening bracket is closed by the same type and in the right 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. Repeated replace

Strip inner 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 openers; on closer, pop and compare. Stack must be empty at end.

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

Tradeoff:

Adyen-specific tips

Adyen uses stack-based parsers extensively in their card scheme message validators, so they expect candidates to identify the stack pattern immediately and verify empty-stack termination.

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

Practice these live with InterviewChamp.AI →