PythonStudio
Interview Problems

Valid Parentheses

easy · stack

You are given a string `s` that contains only the characters `(`, `)`, `{`, `}`, `[`, `]`. Decide whether the string is valid: every opening bracket must be closed by the same type of bracket, and brackets must close in the correct order — the most recently opened bracket must be the first one closed. An empty string counts as valid. Input: `s` (a string of brackets). Output: True if the string is valid, otherwise False. Example: s = "()[]{}" -> True. Example: s = "([)]" -> False, because the square bracket closes before the round bracket that was opened after it.

Starter code

def is_valid(s: str) -> bool:
    """Return True if every bracket is closed in the correct order."""
    pass

Enable JavaScript to edit this code and run the hidden tests in your browser. Each test has a five-second execution limit. Your drafts and solved progress stay in this browser.

Return to the Python compiler