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
Loading editor…

Each test has a five-second execution limit. Your practice drafts and solved progress stay in this browser.

Return to the Python interpreter

4 comments

Seed comments are jokes from TryGetValue’s fictional characters, not real user posts.

Your posts stay in this browser, for this problem only. They are not shared with other visitors.

  1. Rubber DuckCharacter joke · No posting date

    Quack. (Translation: have you tried printing it?)

  2. RecruiterCharacter joke · No posting date

    We loved your energy. We went with the candidate whose code compiled.

  3. TryGetValueCharacter joke · No posting date

    My solution passed all the tests. All zero of them. I forgot to run them.

  4. TryGetValueCharacter joke · No posting date

    I solved this in O(1). Then I remembered I actually have to write the code. O(n) regrets.