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
Minimum Operations to Make Character Frequencies Equal INPUT String s = "abc" 'a' 'b' 'c' Character Frequencies: Char Freq 'a' 1 'b' 1 'c' 1 Operations: Delete, Insert, Change to next letter (cannot change 'z' to 'a') ALGORITHM STEPS 1 Count Frequencies Count each char occurrence 2 Find Target Frequency Try each possible target 3 Calculate Operations Min ops for each target 4 Return Minimum Best result across targets Analysis for s="abc": Target freq = 1 All chars have freq 1 Already balanced! Operations needed = 0 FINAL RESULT String is already "good"! 'a' 'b' 'c' freq=1 freq=1 freq=1 OK Output: 0 No operations needed! All characters appear with equal frequency. Key Insight: Smart Target Selection iterates through all possible target frequencies (0 to max_freq). For each target, calculate minimum operations considering: deletions, insertions, and character shifts. When all frequencies already match (like "abc"), no operations are needed -- > optimal solution is 0. TutorialsPoint - Minimum Operations to Make Character Frequencies Equal | Smart Target Selection
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