Skip to the solution
EasyDSA11 min read

How do you check for valid/balanced parentheses?

690 views

The problem

Question presented to candidate: "Given a string that contains only the characters ( ) [ ] { }, write a Python function that returns True if every bracket is closed by the same kind of bracket in the correct order, and False otherwise. Talk me through the edge cases."

What a strong answer should cover:

  • Use a stack because the most recently opened bracket must close first (last in, first out).
  • The three failure cases: a closer with an empty stack, a closer that does not match the top, and openers left over at the end.
  • O(n) time and O(n) space, with the early exit on odd length and on the first mismatch.
  • Why a single counter only works for one bracket type: it cannot see order, so ([)] slips through.
  • Python specifics: a list used as a stack with append, pop and stack[-1]; a dict mapping closer to opener; stack.pop() on an empty list raises IndexError, so check not stack first.

Clarifying questions expected:

  • "Can the string contain characters other than brackets?"
  • "Should an empty string count as valid?"

Code / implementation expected: Yes โ€” a short Python function using a list as the stack and a dict of pairs.

  • stack
  • parentheses

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

11 min read ยท 11 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonStack-based validator on normal and edge-case inputs
PythonWhy one counter per bracket type is not enough

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 20 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextEasy

What is recursion and what is a base case?

Continue