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 s to 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
Make Character Frequencies Equal: "aab" → Equal FrequenciesInput String: "aab"afreq: 2bfreq: 1cfreq: 0Apply Operations (Target: all frequencies = 1)1 operation: change 'a' to 'c'afreq: 1bfreq: 1cfreq: 1Result: All characters have equal frequency (1 operation)
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
Asked in
Google 25 Microsoft 18 Amazon 15
25.0K Views
Medium Frequency
~35 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen