Remove Letter To Equalize Frequency — LeetCode 2423 Python Solution
- Problem
- #2423
- Pattern
- Hash Map
- Reading time
- 2 min
- Source
- leetcode.com
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
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 FalseComplexity
| Measure | Complexity |
|---|---|
| Time | O(n + C^2) |
| Space | O(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.