File: remove-outermost-parentheses/solution.py

Date: 2026-06-06

Time: 18:48

Purpose

This file is a self-contained solution and test suite for LeetCode 1021: Remove Outermost Parentheses. It owns the algorithm for decomposing a valid parentheses string into its primitive components and stripping the outermost layer from each primitive.

Key Components

Solution.removeOuterParentheses(s: str) -> str

The single method on the Solution class. Takes a valid parentheses string s and returns a new string with the outermost parentheses of each primitive decomposition removed.

A primitive parentheses string is one that cannot be split into two non-empty valid parentheses strings. For example, (()()) is primitive but (())(()) is not — it decomposes into (()) and (()).

TestRemoveOuterParentheses

Seven test cases covering the LeetCode examples, edge cases (empty string, single primitive ()), deeply nested input, and multiple adjacent primitives that all reduce to empty.

Patterns

Depth-counter gate. The algorithm uses a single integer depth as a state machine to decide whether each character belongs to an outer or inner layer. The key insight: when you encounter ( and depth transitions from 0→1, that's an outer open paren — skip it. When you encounter ) and depth transitions from 1→0, that's an outer close — skip it. Everything else is inner content to keep.

The two conditionals implement this asymmetrically but equivalently:

This is an O(n) single-pass algorithm with O(n) space for the result list.

Dependencies

Imports: Only unittest from the standard library — no external dependencies.

Imported by: The "imported by" list in the prompt is misleading. Those ~400+ test files don't actually import this module — that list appears to be an artifact of the repo's structure where every test_solution.py follows the same pattern. The actual test for this solution is inline in the same file.

Flow

1. Initialize empty result list and depth = 0

2. For each character in s:

3. Join and return

The depth counter naturally resets to 0 at the boundary between primitives, so multiple primitives in a single string are handled without any explicit delimiter detection.

Invariants

Error Handling

None. The function assumes valid input per the problem constraints. Empty string is handled gracefully (the loop body never executes, returning ""). There are no exceptions, no assertions, no input validation.

Topics to Explore

Beliefs