Skip to main content

2. Valid Parentheses

easyAsked at Box

Validate balanced brackets using a stack — Box uses this pattern when parsing file path tokens and permission expression syntax.

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

Problem

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

Constraints

  • 1 <= s.length <= 10^4
  • s consists only of bracket characters

Examples

Example 1

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

Example 2

Input
s = "(]"
Output
false

Approaches

1. Brute force

Repeatedly remove inner pairs until empty.

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; on a closer pop and verify match. Stack must be empty at end.

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

Tradeoff:

Box-specific tips

Box graders look for clean stack-based parsing — they reuse this exact pattern for validating share-link permission DSL tokens.

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

Practice these live with InterviewChamp.AI →