Valid Parentheses

Python data engineering interview problem. Difficulty: beginner. Pattern: Stacks. About 10 minutes. Free to practice.

Check whether brackets are correctly matched and nested. Treat this as a production helper: match the contracted return shape, including empty and duplicate inputs.

Code, math and configuration files use brackets that come in pairs: (), [] and {}. A bracket that is opened must be closed, in the right order, by the same kind of bracket. Write a function valid_parentheses(s) that takes a string made only of these 6 characters and returns True if the brackets are balanced, otherwise False. A string is valid when every opening bracket is closed by the same type of bracket, and brackets close in the correct order. '()[]{}' is valid. '(]' is not valid, because ( is closed by the wrong kind of bracket. '([)]' is not valid either, because the brackets cross each other. Keep the print lines in the editor.

Requirements

  • Return True only if every bracket is closed by the right type.
  • Brackets must close in the correct order. The most recently opened one must be closed first.
  • Return False if some bracket is never closed or if a closing bracket has no opening one.
  • An empty string is valid.

Constraints

  • The string only contains the characters (, ), [, ], { and }.
  • The result is a Python True or False.

Examples

Input: valid_parentheses('()[]{}') Output: True Each close matches the latest open.

Topics: lakebench, python, stack, brackets.

More Python interview questions · All interview problems · Learn data engineering

beginner

Valid Parentheses

Interview-style drill: Check whether brackets are correctly matched and nested.

Implement `valid_parentheses(s: str) -> bool` for (), [], {}. Example: `"()[]{}"` → `True`, `"(]"` → `False`. Keep the harness.