DDSA Solutions

Minimum Deletions

Time: O(n*m)
Space: O(n*m)

Problem Overview

Minimum deletions to make string have distinct character frequencies.

Advertisement

Intuition

Minimum deletions to make string have distinct character frequencies. Sort frequencies, greedily decrement.

Algorithm

  1. 1Count frequencies. Sort descending. For each freq: if already used: decrement until unique or 0.

Common Pitfalls

  • Same as LC 1647. Use a set of used frequencies. Greedy: reduce until you find unused frequency or 0.
Minimum Deletions.java
Java
// Approach: LCS-based. Min deletions = (len(s1) - LCS) + (len(s2) - LCS).
// Time: O(n*m) Space: O(n*m)
class Solution {
    static int minDeletions(String s) {
        int n = s.length();
        String rev = new StringBuilder(s).reverse().toString();
        return n - longestCommonSubsequence(s, rev);
    }

    static int longestCommonSubsequence(String s1, String s2) {
        int n = s1.length();
        int[][] dp = new int[n + 1][n + 1];

        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= n; j++) {
                if (s1.charAt(i - 1) == s2.charAt(j - 1))
                    dp[i][j] = 1 + dp[i - 1][j - 1];
                else
                    dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
            }
        }

        return dp[n][n];
    }
}
Advertisement
Was this solution helpful?