LeetCode #3389 — HARD

Minimum Operations to Make Character Frequencies Equal

Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.

Solve on LeetCode
The Problem

Problem Statement

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.

Example 1:

Input: s = "acab"

Output: 1

Explanation:

We can make s good by deleting one occurrence of character 'a'.

Example 2:

Input: s = "wddw"

Output: 0

Explanation:

We do not need to perform any operations since s is initially good.

Example 3:

Input: s = "aaabc"

Output: 2

Explanation:

We can make s good by applying these operations:

  • Change one occurrence of 'a' to 'b'
  • Insert one occurrence of 'c' into s

Constraints:

  • 3 <= s.length <= 2 * 104
  • s contains only lowercase English letters.
Patterns Used

Roadmap

  1. Brute Force Baseline
  2. Core Insight
  3. Algorithm Walkthrough
  4. Edge Cases
  5. Full Annotated Code
  6. Interactive Study Demo
  7. Complexity Analysis
Step 01

Brute Force Baseline

Problem summary: 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.

Baseline thinking

Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.

Pattern signal: Hash Map · Dynamic Programming

Example 1

"acab"

Example 2

"wddw"

Example 3

"aaabbc"

Related Problems

  • Minimum Number of Steps to Make Two Strings Anagram (minimum-number-of-steps-to-make-two-strings-anagram)
Step 02

Core Insight

What unlocks the optimal approach

  • The order of the letters in the string is irrelevant.
  • Compute an occurrence array <code>occ</code> where <code>occ[x]</code> is the number of occurrences of the <code>x<supth</sup></code> character of the alphabet. How do the described operations change <code>occ</code>?
  • We have three types of operations: increase any <code>occ[x]</code> by 1, decrease any <code>occ[x]</code> by 1, or decrease any <code>occ[x]</code> by 1 and simultaneously increase <code>occ[x + 1]</code> by 1 at the same time. To make <code>s</code> good, we need to make <code>occ</code> good. <code>occ</code> is good if and only if every <code>occ[x]</code> equals either 0 or some constant <code>c</code>.
  • If you know the value of <code>c</code>, how can you calculate the minimum operations required to make <code>occ</code> good?
  • Observation 1: It is never optimal to apply the third type of operation (simultaneous decrease and increase) on two continuous elements <code>occ[x]</code> and <code>occ[x + 1]</code>. Instead, we can decrease <code>occ[x]</code> by 1 then increase <code>occ[x + 2]</code> by 1 to achieve the same effect.
  • Observation 2: It is never optimal to increase an element of <code>occ</code> then decrease it, or vice versa.
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03

Algorithm Walkthrough

Iteration Checklist

  1. Define state (indices, window, stack, map, DP cell, or recursion frame).
  2. Apply one transition step and update the invariant.
  3. Record answer candidate when condition is met.
  4. Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04

Edge Cases

Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Largest constraint values
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05

Full Annotated Code

Source-backed implementations are provided below for direct study and interview prep.

// Accepted solution for LeetCode #3389: Minimum Operations to Make Character Frequencies Equal
class Solution {
  public int makeStringGood(String s) {
    int ans = s.length();
    int[] count = new int[26];

    for (final char c : s.toCharArray())
      ++count[c - 'a'];

    final int maxCount = Arrays.stream(count).max().getAsInt();
    for (int target = 1; target <= maxCount; ++target)
      ans = Math.min(ans, getMinOperations(count, target));

    return ans;
  }

  private int getMinOperations(int[] count, int target) {
    // dp[i] represents the minimum number of operations to make the frequency of
    // (i..25)-th (0-indexed) letters equal to `target`.
    int[] dp = new int[27];

    for (int i = 25; i >= 0; --i) {
      // 1. Delete all the i-th letters.
      int deleteAllToZero = count[i];
      // 2. Insert/delete the i-th letters to have `target` number of letters.
      int deleteOrInsertToTarget = Math.abs(target - count[i]);
      dp[i] = Math.min(deleteAllToZero, deleteOrInsertToTarget) + dp[i + 1];
      if (i + 1 < 26 && count[i + 1] < target) {
        final int nextDeficit = target - count[i + 1];
        // Make the frequency of the i-th letter equal to the `target` or 0.
        final int needToChange = count[i] <= target ? count[i] : count[i] - target;
        final int changeToTarget = (nextDeficit > needToChange)
                                       // 3. Change all the i-th letters to the next letter and then
                                       // insert the remaining deficit for the next letter.
                                       ? needToChange + (nextDeficit - needToChange)
                                       // 4. Change `nextDeficit` i-th letters to the next letter
                                       // and then delete the remaining i-th letters.
                                       : nextDeficit + (needToChange - nextDeficit);
        dp[i] = Math.min(dp[i], changeToTarget + dp[i + 2]);
      }
    }

    return dp[0];
  }
}
Step 06

Interactive Study Demo

Use this to step through a reusable interview workflow for this problem.

Press Step or Run All to begin.
Step 07

Complexity Analysis

Time
O(n × m)
Space
O(n × m)

Approach Breakdown

RECURSIVE
O(2ⁿ) time
O(n) space

Pure recursion explores every possible choice at each step. With two choices per state (take or skip), the decision tree has 2ⁿ leaves. The recursion stack uses O(n) space. Many subproblems are recomputed exponentially many times.

DYNAMIC PROGRAMMING
O(n × m) time
O(n × m) space

Each cell in the DP table is computed exactly once from previously solved subproblems. The table dimensions determine both time and space. Look for the state variables — each unique combination of state values is one cell. Often a rolling array can reduce space by one dimension.

Shortcut: Count your DP state dimensions → that’s your time. Can you drop one? That’s your space optimization.
Coach Notes

Common Mistakes

Review these before coding to avoid predictable interview regressions.

Mutating counts without cleanup

Wrong move: Zero-count keys stay in map and break distinct/count constraints.

Usually fails on: Window/map size checks are consistently off by one.

Fix: Delete keys when count reaches zero.

State misses one required dimension

Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.

Usually fails on: Correctness breaks on cases that differ only in hidden state.

Fix: Define state so each unique subproblem maps to one DP cell.