Skip to main content

2. Valid Parentheses

easyAsked at Coupang

Validate a string of brackets using a stack — Coupang asks this to gauge stack reasoning before search-query parsing rounds.

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

Problem

Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string 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 parentheses only '()[]{}'

Examples

Example 1

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

Example 2

Input
s = "([)]"
Output
false

Approaches

1. Brute force

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

Time
O(n^2)
Space
O(n)
while (s.includes('()')||s.includes('[]')||s.includes('{}'))
  s = s.replace('()','').replace('[]','').replace('{}','');
return s === '';

Tradeoff:

2. Stack

Push opens, pop and match on closes. Linear scan with stack.

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

Tradeoff:

Coupang-specific tips

Coupang asks you to extend this to validate query-DSL filter expressions used in product-search parsing.

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

Practice these live with InterviewChamp.AI →