Minimum Operations to Make Character Frequencies Equal - Problem
You are given a string s. A string t is called good if all characters of t occur the same number of times.
You can perform the following operations any number of times:
- Delete a character from
s - Insert a character in
s - Change a character in
sto its next letter in the alphabet
Note that you cannot change 'z' to 'a' using the third operation.
Return the minimum number of operations required to make s good.
Input & Output
Example 1 — Simple Case
$
Input:
s = "abc"
›
Output:
0
💡 Note:
All characters already appear exactly once, so the string is already good. No operations needed.
Example 2 — Need Balancing
$
Input:
s = "aab"
›
Output:
1
💡 Note:
We have a=2, b=1. To make all frequencies equal to 1, we need 1 operation: change one 'a' to 'c' to get "acb" where a=1, b=1, c=1.
Example 3 — Multiple Operations
$
Input:
s = "aaaa"
›
Output:
3
💡 Note:
We have a=4. To make it good, we can change to get a=1, b=1, c=1, d=1. This requires 3 operations: change 'a'→'b', 'a'→'c', 'a'→'d'.
Constraints
- 1 ≤ s.length ≤ 105
- s consists of only lowercase English letters
Visualization
Tap to expand
Understanding the Visualization
1
Input Analysis
Count frequency of each character in string
2
Find Target
Determine optimal target frequency for all characters
3
Apply Operations
Use delete, insert, change operations to reach target
Key Takeaway
🎯 Key Insight: Test only promising target frequencies based on existing character counts and use transformation chains to minimize operations
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code