Remove Letter To Equalize Frequency — LeetCode 2423 Python Solution

EasyHash TableStringCounting
Problem
#2423
Pattern
Hash Map
Reading time
2 min

The problem

You are given a 0-indexed string word, consisting of lowercase English letters. You need to select one index and remove the letter at that index from word so that the frequency of every letter present in word is equal.

Example

Input
word = "abcc"
Output
true
Explanation
Select index 3 and delete it: word becomes "abc" and each character has a frequency of 1.

Python solution

Python
class Solution:
    def equalFrequency(self, word: str) -> bool:
        cnt = Counter(word)
        for c in cnt.keys():
            cnt[c] -= 1
            if len(set(v for v in cnt.values() if v)) == 1:
                return True
            cnt[c] += 1
        return False

Complexity

MeasureComplexity
TimeO(n + C^2)
SpaceO(C) auxiliary

Pattern: Hash Map

Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 2423. Remove Letter To Equalize Frequency is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table and Counting.

The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2423. Remove Letter To Equalize Frequency?
LeetCode 2423. Remove Letter To Equalize Frequency is rated Easy on LeetCode.
What is the time complexity of LeetCode 2423. Remove Letter To Equalize Frequency?
The Python solution on this page runs in O(n + C^2).
What is the space complexity of LeetCode 2423. Remove Letter To Equalize Frequency?
The Python solution on this page uses O(C) auxiliary space.
What topics does LeetCode 2423. Remove Letter To Equalize Frequency cover?
LeetCode 2423. Remove Letter To Equalize Frequency is tagged Hash Table, String and Counting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview