Problem solution · Java

Minimum Operations to Make Character Frequencies Equal

Minimum Operations to Make Character Frequencies Equal: a Java solution using dynamic programming. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Dynamic programming
Source
walkccc LeetCode Solutions
Length
45 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Dynamic programming

For Minimum Operations to Make Character Frequencies Equal, the implementation records answers for smaller states and reuses them to build the requested result without repeating work.

  1. Define precisely what one DP state represents.
  2. Establish the base cases before transitions are evaluated.
  3. Process states in dependency order and combine only already-known values.

Code notes

  • 45 lines of Java from the credited upstream file 3389.java.
  • The implementation visibly relies on sequence storage, cached states.
  • 3 loop blocks detected.

Complexity

Multiply the number of reachable states by the work performed for each transition, then include the stored state table in memory usage.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codeMinimum Operations to Make Character Frequencies Equal · JavaJava
Use this to learn the idea, then write your own version.
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];  }} 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗