#3389

Minimum Operations to Make Character Frequencies Equal

Hard
Hash TableStringDynamic ProgrammingCountingEnumerationHash MapArray
LeetCode ↗

Approaches

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

Intuition

Time O(n)Space O(n)

Instead of checking every possible frequency, we can directly calculate the operations needed based on the frequency counts. We can use a frequency count array and determine the operations needed to balance the frequencies more efficiently.

⚙️

Algorithm

4 steps
  1. 1Step 1: Count the frequency of each character in the string using an array of size 26.
  2. 2Step 2: Calculate the total number of characters and the number of unique frequencies.
  3. 3Step 3: For each unique frequency, calculate the number of operations needed to convert all character counts to that frequency.
  4. 4Step 4: Return the minimum operations found.
solution.py20 lines
1from collections import Counter
2
3def min_operations_optimal(s):
4    freq = Counter(s)
5    count_freq = [0] * 26
6    for count in freq.values():
7        count_freq[count] += 1
8    total_chars = len(s)
9    min_operations = float('inf')
10    
11    for target_freq in range(1, total_chars + 1):
12        operations = 0
13        for i in range(1, 26):
14            if count_freq[i] > 0:
15                if i < target_freq:
16                    operations += (target_freq - i) * count_freq[i]
17                else:
18                    operations += (i - target_freq) * count_freq[i]
19        min_operations = min(min_operations, operations)
20    return min_operations

Complexity note: The time complexity is O(n) because we only traverse the string a few times, and the space complexity is O(n) due to the frequency map storing character counts.

  • 1Understanding character frequency is crucial to solving this problem efficiently.
  • 2Operations can be thought of as balancing the character counts to a common frequency.

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