Skip to main content

2. Valid Parentheses

easyAsked at SoFi

Validate bracket matching using a stack — SoFi uses this to gauge fluency with stack-based parsers for transaction-rule strings.

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

Problem

Given a string containing '()[]{}', determine if every opening bracket has a matching closing bracket in the correct order.

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

Repeatedly remove matched pairs until none remain.

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 a closer, pop and compare. Linear time and clean — the answer SoFi expects on a rules-parser warmup.

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

Tradeoff:

SoFi-specific tips

SoFi values candidates who immediately suggest a stack and relate it to validating well-formed expressions in their loan-document rule-engine.

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

Practice these live with InterviewChamp.AI →