Skip to main content

2. Valid Parentheses

easyAsked at Coursera

Validate that a string of brackets is well-formed — Coursera uses this to test stack discipline in a course-syntax-checker context.

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

Problem

Given a string s containing only '()[]{}', determine if the input string has matching open/close brackets in the right order. Empty string is valid.

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. Replace pairs repeatedly

Strip out () [] {} pairs until no change; valid iff empty.

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

Tradeoff:

2. Stack

Push openers; on closer, pop and compare against expected match.

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:

Coursera-specific tips

Coursera interviewers reward candidates who tie this to validating quiz-template DSL or LaTeX-in-content rendering — the team owns the assessment authoring pipeline.

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

Practice these live with InterviewChamp.AI →