File: remove-letter-to-equalize-frequency/solution.py

Date: 2026-06-06

Time: 18:47

remove-letter-to-equalize-frequency/solution.py

Purpose

This file solves LeetCode 2423: Remove Letter To Equalize Frequency. It determines whether you can remove exactly one character from a string so that every remaining distinct character appears the same number of times.

Key Components

canequalfrequency(word: str) -> bool — The sole public function. Takes a lowercase letter string of length 2–100 and returns True if deleting exactly one character makes all remaining character frequencies equal.

Patterns

Brute-force simulation. Rather than reasoning about frequency counts analytically (which is notoriously error-prone for this problem due to many edge cases), the solution tries every possible single deletion and checks whether the result has uniform frequency. This is the "just simulate it" idiom — trade O(n^2) time for zero risk of missing a corner case.

The uniformity check len(set(counts.values())) == 1 is a standard Python idiom: if all values in a Counter are equal, the set of values has exactly one element.

Dependencies

Flow

1. Iterate i over every index [0, len(word)).

2. For each i, build a new string with index i removed via word[:i] + word[i+1:].

3. Count character frequencies of the shortened string with Counter.

4. Check if all frequencies are identical: len(set(counts.values())) == 1.

5. If any deletion produces uniform frequencies, return True immediately (short-circuit).

6. If no deletion works, return False.

Invariants

Error Handling

None. The function assumes valid input per the LeetCode contract (lowercase English letters, length 2–100). No exceptions are raised or caught.

Complexity

For n ≤ 100 this is trivially fast. An O(n) analytical approach exists but is much harder to get right — this problem is infamous for tricky edge cases (e.g., "aazz", "abc", "aaaa").

Topics to Explore

Beliefs