#3085

Minimum Deletions to Make String K-Special

Medium
Hash TableStringGreedySortingCountingHash MapSliding Window
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(n)
💡

Intuition

Time O(n log n)Space O(n)

The optimal approach involves counting the frequencies of characters, sorting them, and then determining the minimum deletions needed to ensure that the difference between the maximum and minimum frequencies is within k. This is efficient and leverages sorting.

⚙️

Algorithm

4 steps
  1. 1Step 1: Count the frequency of each character in the string.
  2. 2Step 2: Store the frequencies in a list and sort it.
  3. 3Step 3: Use a sliding window to find the longest subarray where the difference between the maximum and minimum frequencies is less than or equal to k.
  4. 4Step 4: Calculate the minimum deletions as the total number of characters minus the size of the longest valid subarray.
solution.py14 lines
1# Full working Python code
2from collections import Counter
3
4def min_deletions_optimal(word, k):
5    freq = Counter(word)
6    freq_list = sorted(freq.values())
7    left = 0
8    max_length = 0
9    for right in range(len(freq_list)):
10        while freq_list[right] - freq_list[left] > k:
11            left += 1
12        max_length = max(max_length, right - left + 1)
13    return len(word) - max_length
14

Complexity note: The time complexity is dominated by the sorting step, which is O(n log n), while counting frequencies is O(n). The space complexity is O(n) due to storing the frequency counts.

  • 1Understanding character frequency is crucial to solving this problem efficiently.
  • 2Using sorting and a sliding window approach can drastically reduce the complexity from brute-force.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.