Skip to main content

2. Valid Parentheses

easyAsked at Autodesk

Determine if a string of brackets is properly opened and closed.

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

Problem

Given a string containing the characters '()', '[]', and '{}', determine if the input string is valid. Brackets must close in the correct order and every opener must have a matching closer of the same type.

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 strip matched pairs 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 and pop on closers, verifying the match. Empty stack at the end means valid.

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

Tradeoff:

Autodesk-specific tips

Autodesk uses stacks heavily for undo history in DWG/Revit edits, so this maps directly to their command-pattern expectations.

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

Practice these live with InterviewChamp.AI →