Skip to main content

2. Valid Parentheses

easyAsked at Canva

Determine if a string of brackets is balanced — Canva uses this to test how you reason about stack-based parsing for nested layer trees.

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

Problem

Given a string s containing just '(', ')', '{', '}', '[' and ']', determine if the input is valid. Open brackets must be closed by the same type 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 replace

Repeatedly remove '()', '[]', '{}' until no change.

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 and compare on closers. Any mismatch or leftover means invalid.

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

Tradeoff:

Canva-specific tips

Canva interviewers like to see you map this to real editor cases like nested groups and frames, signaling you understand layered design objects.

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

Practice these live with InterviewChamp.AI →