Skip to main content

2. Valid Parentheses

easyAsked at Revolut

Use a stack to validate matching brackets, a classic Revolut warm-up that mirrors validating nested transaction blocks in a settlement message.

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

Problem

Given a string s containing just the characters '()[]{}', determine if the input string is valid. Open brackets must be 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 strip empty pairs until stable.

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

Tradeoff:

2. Stack

Push openers; on closer pop and compare. Empty stack at end means balanced.

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

Tradeoff:

Revolut-specific tips

Revolut interviewers like you to draw the analogy to nested ISO-20022 payment messages — bonus points for asking whether truncated streams should fail-closed.

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

Practice these live with InterviewChamp.AI →