LeetCode 20: Valid Parentheses — Python Solution

LeetCode 20: Valid Parentheses is an Easy stack problem. This Python walkthrough develops an expected-closer stack solution, ties every code decision to a concrete invariant, and includes the regression check used before publication.

This independent guide paraphrases the task rather than reproducing LeetCode’s prompt. Use the official page for the exact statement, examples, constraints, and submission runner.

DifficultyEasy
TopicStack
Reusable patternexpected-closer stack
ComplexityO(n) time and O(n) space

Recognizing the pattern

A stack is appropriate when the newest unresolved item must be handled before older unresolved items.

For this problem specifically, push the required closing symbol for every opener; each closer must match the most recently expected symbol. The invariant worth writing beside the code is: The stack contains exactly the closing symbols needed for unmatched openers.

Step-by-step algorithm

  1. Identify the input state consumed by isValid(s) and initialize the data required by the expected-closer stack pattern.
  2. Push the required closing symbol for every opener; each closer must match the most recently expected symbol.
  3. After each update, verify the page’s central invariant: The stack contains exactly the closing symbols needed for unmatched openers.
  4. Finish only after the boundary behavior is covered: A closer on an empty stack or leftover openers makes the string invalid.

Python solution

class Solution:
    def isValid(self, s):
        expected = []
        pairs = {"(": ")", "[": "]", "{": "}"}
        for char in s:
            if char in pairs:
                expected.append(pairs[char])
            elif not expected or expected.pop() != char:
                return False
        return not expected

Reading the implementation

The main entry point is isValid(s). The named working state includes expected, pairs; those variables make the expected-closer stack state visible instead of hiding it in incidental control flow.

A single main loop advances the algorithm, which is the key reason the traversal does not revisit already resolved input unnecessarily. Early returns stop as soon as the answer is forced, avoiding work that cannot change the result. In concrete terms, push the required closing symbol for every opener; each closer must match the most recently expected symbol.

Correctness argument

Initialization. The data structure starts with exactly the information known before any input element is processed.

Preservation. Push the required closing symbol for every opener; each closer must match the most recently expected symbol. Each update records the current item without invalidating earlier decisions; consequently, the stack contains exactly the closing symbols needed for unmatched openers.

Termination. The traversal consumes a finite input or finite state space. At the end, the invariant covers the complete input, which is precisely the condition required for the returned result.

Complexity and trade-offs

O(n) time and O(n) space. The auxiliary-space figure excludes the returned output unless the output itself is the structure being built.

Repeated rescanning can find the same dependency without a stack, but it usually hides the nesting invariant and costs more time. That comparison is useful in an interview because it explains why the final implementation is preferable, not merely that it passes.

Regression check

The published implementation belongs to a 100-problem suite that is compiled and exercised behaviorally before deployment.

One reference assertion from that suite is shown below. It targets the normal path while the edge conditions in the next section cover the failure-prone boundaries.

assert Solution().isValid("()[]{}")

Common mistakes and edge cases

  • Problem-specific boundary: A closer on an empty stack or leftover openers makes the string invalid.
  • Pattern-level pitfall: Check emptiness before reading the top and decide whether an operator, delimiter, or node is consumed before or after the pop.
  • Invariant check: after every update, confirm that the stack contains exactly the closing symbols needed for unmatched openers.

Interview review checklist

  • Explain why expected-closer stack matches the structure of this input.
  • State the invariant in one sentence before tracing code: The stack contains exactly the closing symbols needed for unmatched openers.
  • Derive O(n) time and O(n) space from how many times each element or state is visited.
  • Test the boundary explicitly: A closer on an empty stack or leftover openers makes the string invalid.

Browse the searchable 100 LeetCode Python Solutions hub. Previous: 452. Minimum Number of Arrows to Burst Balloons · Next: 71. Simplify Path