Skip to main content

2. Valid Parentheses

easyAsked at Unity

Check whether brackets are balanced using a stack. Unity uses this to test scene-graph traversal intuition.

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

Problem

Given a string s containing only the characters '()[]{}', determine if the input string is valid. An input is valid if brackets are closed by the same type and in the correct order.

Constraints

  • 1 <= s.length <= 10^4
  • s consists only of '()[]{}'

Examples

Example 1

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

Example 2

Input
s='(]'
Output
false

Approaches

1. Replace pairs repeatedly

Loop replacing '()','[]','{}' with '' until stable, then check empty.

Time
O(n^2)
Space
O(n)
let prev;
while (prev !== s) { prev = s; s = s.replace(/\(\)|\[\]|\{\}/g,''); }
return s === '';

Tradeoff:

2. Stack scan

Push openers, pop+match on closers. Empty stack at end means balanced.

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

Tradeoff:

Unity-specific tips

Unity wants you to relate the stack to a render-state stack you'd push/pop while walking a scene graph each frame.

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

Practice these live with InterviewChamp.AI →