Skip to main content

2. Valid Parentheses

easyAsked at GitHub

Determine if a string of brackets is balanced — GitHub uses this as a warm-up before diving into nested merge conflict markers and diff hunk delimiters.

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

Problem

Given a string s containing only the characters '(', ')', '{', '}', '[', ']', determine if the input string is valid. Brackets must close in the correct order with matching pairs.

Constraints

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

Examples

Example 1

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

Example 2

Input
s = "([)]"
Output
false

Approaches

1. Brute force

Repeatedly strip matching adjacent pairs until empty or stuck.

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, pop and verify match on closers. Empty stack at end means valid.

Time
O(n)
Space
O(n)
function isValid(s) {
  const pairs = { ')': '(', ']': '[', '}': '{' };
  const stack = [];
  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:

GitHub-specific tips

GitHub frames this as 'how would you validate conflict marker nesting in a 3-way merge?' — name-drop the stack-as-AST analogy.

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

Practice these live with InterviewChamp.AI →