File: valid-parentheses/solution.py

Date: 2026-06-06

Time: 19:39

valid-parentheses/solution.py

Purpose

This file implements the solution to LeetCode #20 — Valid Parentheses. It owns a single responsibility: determining whether a string consisting of bracket characters ()[]{} has every opener properly matched and nested with its corresponding closer.

Key Components

is_valid(s: str) -> bool — The sole public function. Contract: given a string containing only the six bracket characters, returns True if and only if every opening bracket has a matching closing bracket in the correct nesting order.

Three internal pieces do the work:

Patterns

Stack-based bracket matching — the textbook approach. The match dict serves double duty: it's both a lookup table and a set membership test, which keeps the code tight.

Early return on mismatch — the function short-circuits as soon as it finds a closer with no matching opener (not stack) or a mismatched opener (stack.pop() != match[ch]). This avoids unnecessary work on malformed input.

Implicit else for openers — any character not in match is treated as an opener and pushed onto the stack. This works because the problem guarantees the input contains only the six bracket characters.

Dependencies

Imports: None. This is a pure function with zero dependencies — no standard library, no project utilities.

Imported by: The "Imported By" list in the prompt shows hundreds of test files across the repo reference this. That's misleading — those are test files for *other* problems that happen to share a common test harness pattern, not actual consumers of isvalid. The real consumer is valid-parentheses/testsolution.py.

Flow

1. Initialize empty stack and the match mapping {')':'(', ']':'[', '}':'{'}.

2. Iterate character-by-character through s:

3. After the loop, return not stackTrue only if every opener was consumed by a closer.

Invariants

Error Handling

There is none in the traditional sense — no exceptions raised, no error codes. The function communicates failure purely through its boolean return value. It is resilient to edge cases:

Topics to Explore

Beliefs