File: palindrome-permutation/solution.py

Date: 2026-06-06

Time: 18:28

Purpose

This file solves LeetCode 266 — Palindrome Permutation. It determines whether any rearrangement of the input string could form a palindrome. It doesn't find the permutation — just answers yes/no.

Key Components

canPermutePalindrome(s: str) -> bool — The sole public function. It exploits the mathematical property that a string can be rearranged into a palindrome if and only if at most one character has an odd frequency. Even-length palindromes need all characters paired; odd-length palindromes allow exactly one unpaired center character.

Flow

1. Counter(s) builds a frequency map: {"a": 2, "b": 1} for "aab".

2. .values() yields the raw counts.

3. c % 2 for c in ... maps each count to 0 (even) or 1 (odd) — a generator of bits.

4. sum(...) counts how many characters have odd frequency.

5. <= 1 enforces the palindrome invariant.

The entire logic is a single expression. For input "aab": counts are {a:2, b:1}, odd counts = 1, result = True (rearranges to "aba").

Patterns

Counting-to-parity reduction — The solution doesn't care about the actual counts, only their parity. This is a common idiom in palindrome problems. An alternative approach uses XOR on a bitmask (set symmetric difference), but Counter + modular arithmetic is more readable and equally O(n).

Single-expression body — The function fits in one line because the problem has a clean mathematical characterization. No iteration state, no early returns.

Dependencies

Invariants

Error Handling

None. Empty string returns True (sum is 0), which is correct — the empty string is a palindrome. No input validation; the function trusts its caller.

Topics to Explore

Beliefs