File: remove-palindromic-subsequences/solution.py

Date: 2026-06-06

Time: 18:49

remove-palindromic-subsequences/solution.py

Purpose

This file solves LeetCode 1332 — Remove Palindromic Subsequences. It determines the minimum number of steps to remove all characters from a string consisting only of 'a' and 'b', where each step removes a palindromic subsequence (not substring).

The key insight that makes this problem trivial: since the alphabet is only {a, b}, you can always remove all 'a's in one step (they form a palindromic subsequence) and all 'b's in another. So the answer is always 0, 1, or 2.

Key Components

countStrings(s: str) -> int — The core solver. Contract:

The function name countStrings is a misnomer — it counts *steps*, not strings. The LeetCode problem's canonical name is removePalindromeSub.

TestCountStrings — Unit test class covering edge cases: empty string, single char, palindromes, non-palindromes, uniform strings, alternating patterns, and a 1000-char stress test.

Patterns

Dependencies

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

Imported by: The test_solution.py file in the same directory imports this. The massive "Imported By" list in the context is noise — those are *other* problems' test files that happen to share the same unittest import, not actual consumers of countStrings.

Flow

1. Empty check → return 0

2. Initialize two pointers at string boundaries

3. Walk inward comparing s[left] vs s[right]

4. First mismatch → return 2 (need two steps: one for all as, one for all bs)

5. Pointers meet without mismatch → return 1 (string is a palindrome, remove it whole)

Invariants

Error Handling

None. The function handles the empty-string edge case explicitly but has no error paths. Invalid input (non-ab strings) won't crash — the function just checks palindromicity, which is alphabet-agnostic. The answer of 2 would be wrong for strings with 3+ distinct characters, but the problem constrains this.

Topics to Explore

Beliefs