Solving Leetcode Interviews in Seconds with AI: Minimum Deletions to Make Character Frequencies Unique
Introduction
In this blog post, we will explore how to solve the LeetCode problem "1647" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.
Problem Statement
A string s is called good if there are no two different characters in s that have the same frequency. Given a string s, return the minimum number of characters you need to delete to make s good. The frequency of a character in a string is the number of times it appears in the string. For example, in the string "aab", the frequency of 'a' is 2, while the frequency of 'b' is 1. Example 1: Input: s = "aab" Output: 0 Explanation: s is already good. Example 2: Input: s = "aaabbbcc" Output: 2 Explanation: You can delete two 'b's resulting in the good string "aaabcc". Another way it to delete one 'b' and one 'c' resulting in the good string "aaabbc". Example 3: Input: s = "ceabaacb" Output: 2 Explanation: You can delete both 'c's resulting in the good string "eabaab". Note that we only care about characters that are still in the string at the end (i.e. frequency of 0 is ignored). Constraints: 1 <= s.length <= 105 s contains only lowercase English letters.
Explanation
Here's a breakdown of the approach, complexity, and the Python code for solving the problem:
- Frequency Counting: Calculate the frequency of each character in the input string.
- Greedy Deletion: Iterate through the frequencies in descending order. For each frequency, if it's already present in a set of used frequencies, greedily decrement it until it's either unique or zero.
Counting Deletions: Accumulate the number of decrements (deletions) performed.
Runtime Complexity: O(N log N), where N is the length of the string (due to sorting the frequencies).
- Storage Complexity: O(1), as we only use a fixed-size array for frequency counting and a set to track unique frequencies (both of size at most 26).
Code
def min_deletions(s: str) -> int:
"""
Calculates the minimum number of characters to delete to make a string "good".
Args:
s: The input string.
Returns:
The minimum number of deletions required.
"""
freq = [0] * 26
for char in s:
freq[ord(char) - ord('a')] += 1
freq.sort(reverse=True)
deleted_count = 0
used_frequencies = set()
for i in range(26):
if freq[i] == 0:
break # Optimization: Stop if frequencies become zero
while freq[i] > 0 and freq[i] in used_frequencies:
freq[i] -= 1
deleted_count += 1
used_frequencies.add(freq[i])
return deleted_count