Skip to main content

2. Valid Parentheses

easyAsked at TripAdvisor

Determine if a string of brackets is properly balanced and nested.

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 and 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 replace

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

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

Tradeoff:

2. Stack

Push opens, pop and match on close. Single pass.

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

Tradeoff:

TripAdvisor-specific tips

TripAdvisor uses this to check whether you can parse review and itinerary token streams cleanly before scaling to nested filters.

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

Practice these live with InterviewChamp.AI →