Skip to main content

2. Valid Parentheses

easyAsked at N26

Validate whether a string of brackets is balanced using a stack. N26 frames this as a sanity check before deeper questions about bracket-style transaction grouping.

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. Brackets must close in the correct order and every opening bracket must be matched by the same type of closing bracket.

Constraints

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

Examples

Example 1

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

Example 2

Input
s='(]'
Output
false

Approaches

1. Replace pairs repeatedly

Strip empty pairs until no change; check empty result.

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 openers, pop on closers and validate match.

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

Tradeoff:

N26-specific tips

N26 expects you to call out that a stack-style LIFO mirrors how nested transaction-correction reversals must unwind in order.

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

Practice these live with InterviewChamp.AI →