Skip to main content

2. Valid Parentheses

easyAsked at Tesla

Determine if a string of brackets is valid using a stack.

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

Problem

Given a string s containing characters from '()[]{}', determine if every opening bracket has a matching close in the correct order. Return true if balanced.

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. Repeated replace

Strip matching pairs until none left.

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 opens; on close, verify the top matches. Empty stack at end means balanced.

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

Tradeoff:

Tesla-specific tips

Tesla embedded interviewers value pre-sized arrays over JS push/pop when targeting deterministic real-time loops — mention how you'd swap to a fixed-size ring buffer in C++.

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

Practice these live with InterviewChamp.AI →