Skip to main content

2. Valid Parentheses

easyAsked at Dropbox

Determine if a string of brackets is balanced; Dropbox uses this to probe stack reasoning for nested file-tree path parsing.

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

Problem

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

Repeatedly strip innermost pairs until none remain.

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 openings; on closing, pop and verify it matches. Linear single pass.

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

Tradeoff:

Dropbox-specific tips

Dropbox interviewers expect you to call out empty-stack-on-close as a separate edge case — they map it to malformed path segments in the sync protocol.

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

Practice these live with InterviewChamp.AI →