Minimum Deletions to Make String K-Special in Java
In this tutorial, we are going to learn about minimun deletions to make string K-Special in Java. We are given an integer, k, and a string word. Of the letter x in Word, while |y| indicates y's absolute value. If, for every i and j in the string, the product of |freq(word[i]) - freq(word[j])| <= k, then we regard word as k-special. The objective at hand is to determine the minimum number of characters that must be eliminated from string str to guarantee that every character appears exactly once.
Examples:
Example 1:
Input: string = "aabbbccccddddeeeff"
Output: 5
Explanation: The frequencies of each distinct character are as follows:
a -> 2
b -> 3
c -> 4
d -> 4
e -> 3
f -> 2
The following are some potential methods to reduce the minimum number of steps required to make each character unique:
- When one instance of "c" is eliminated, string becomes "aabbbcccddddeeeff."
- When one instance of "d" is eliminated, string becomes "aabbbcccddddeeeff."
- When one instance of "e" is eliminated, string becomes "aabbbcccddddeeeff."
- When one instance of "f" is eliminated, string becomes "aabbbcccddddeeeff."
- String becomes "aabbbccccdddddff" if one occurrence of 'f' and one occurrence of 'e' are removed.
Therefore, the minimum removals required is 5.
Naïve Approach:
Step 1: Create all potential substrings of the input string and determining if each substring is sorted would be a simplistic method of addressing the challenge of determining the lowest number of deletions required to make a string sorted.
Step 2: Next, find the total minimum by computing the least amount of deletions needed to sort each substring.
Step 3: Create each and every substring that the input string can have.
Step 4: Verify the sorting of each substring.
Step 5: Determine how many removals are needed to sort a substring if it isn't already sorted.
Step 6: Keep track of the least amount of deletions for each and every substring.
Step 7: Give back the total minimal amount of deletions.
Filename: MinimumDeletionsDP.java
public class MinimumDeletionsDP { // How to figure out how few deletions are needed to sort the string "s" public static int minimumDeletions(String str) { int len = str.length(); // Keep track of the string's' length. int minDeletions = 0; // Set the required minimum number of deletions to zero. int countBs = 0; // Set the 'b' character count to 0 upon initialization. for (int a = 0; a < len; ++a) { // Verify that 'b' is the current character. if (str.charAt(a) == 'b') { // Increase the number of "b" characters. ++countBs; } else { // Since it's a 'a,' find the minimum between removing the current 'a' and any minimal deletions made in the past, as well as the total number of 'b' characters that have been observed thus far. minDeletions = Math.min(minDeletions + 1, countBs); } } // Return the calculated minimal amount of deletions. return minDeletions; } public static void main(String[] args) { // Given example input string String str = "bbbabaab"; // Determine the least amount of deletions. int answer = minimumDeletions(str); System.out.println("Minimum deletions required are: " + answer); } }
Output:
Minimum deletions required: 3
Time Complexity: The time complexity of the program is O(n).
Space Complexity: The space complexity of the program is O(26).
Approach 1: Using Greedy Algorithm
ALGORITHM:
Step 1: Count the frequency of each character in the input string word and store it in an array A of size 26, where each index represents a lowercase letter in the English alphabet.
Step 2: Iterate through each frequency value X in the array A.
Step 3: Calculate the minimum deletions required to satisfy a condition on the frequency of characters in the string for each frequency x.
Step 4: For every x, update the res variable with the lowest value of both res and cur. The minimal number of deletions needed across all frequencies is stored in res at the end of the outer loop.
Step 5: Keep the least amount of deletions in the res variable and are finally returned.
Filename: MinimumDeletions.java
public class MinimumDeletions { public static void main(String[] args) { // Given example string String str = "aabeeccc"; int kValue = 2; // Use the minimumDeletions function, then output the outcome. int minDeletions = minimumDeletions(str, kValue); System.out.println("Minimum deletions required are: " + minDeletions); } public static int minimumDeletions(String str, int kValue) { int minDeletions = 100000, charCount[] = new int[26]; for (char character: str.toCharArray()) { charCount[character - 'a']++; } for (int count: charCount) { int currentDeletions = 0; for (int frequency: charCount) { currentDeletions += (frequency < count) ? frequency : Math.max(0, frequency - (count + kValue)); } minDeletions = Math.min(minDeletions, currentDeletions); } return minDeletions; } }
Output:
Minimum deletions required: 0
Time Complexity: The time complexity of the program is O(n + 26 * 26).
Space Complexity: The space complexity of the program is O(26).
Approach 2: Using priority queue
ALGORITHM:
Step 1: Create a map, called mp, and initialize it to hold the frequency of each unique character in the text.
Step 2: Set the initial value of a variable, such as cntChar, to the number of characters that must be eliminated in order to make each character's frequency in the string unique.
Step 3: Assign each character's frequency to a priority queue, let's call it pq, and arrange them so that the highest frequency found appears first in the priority queue.
Step 4: Follow the priority_queue iteration until pq is empty, and then determine whether or not pq's top element is equal to its second-top element. If this is confirmed, then the value of cntChar will be increased by 1 and the value of the topmost element of pq will be reduced by 1.
Step 5: If not, pop the highest element in pq.
Step 6: Print the value of cntChar at the end.
Filename: MinimumCharacters.java
import java.util.*; public class MinimumCharacters { // Function to determine the least number of characters that must be eliminated // in order for all character frequencies to be unique static int minimumCountCharacterDeletionsfrequency(char[] string, int length) { // keeps track of the frequency of every unique character in str HashMapmap = new HashMap<>(); // Each unique character's frequency should be stored so that the highest frequency appears at the top. PriorityQueue priorityQueue = new PriorityQueue<>((a, b) -> Integer.compare(b, a)); // keeps track of the minimal number of characters that must be removed // in order for each character's frequency to be unique. int countCharacter = 0; for (int m = 0; m < length; m++) { if (map.containsKey(string[m])) { map.put(string[m], map.get(string[m]) + 1); } else { map.put(string[m], 1); } } for (Map.Entry entry : map.entrySet()) { priorityQueue.add(entry.getValue()); } // Traverse the priority_queue while (!priorityQueue.isEmpty()) { // retains the highest element of pq int freq = priorityQueue.peek(); // Pop the highest element priorityQueue.remove(); if (priorityQueue.isEmpty()) { // Return countCharacter return countCharacter; } if (freq == priorityQueue.peek()) { if (freq > 1) { priorityQueue.add(freq - 1); } // Modify countCharacter countCharacter++; } } return countCharacter; } public static void main(String[] args) { String str = "aaabcbcd"; int length = str.length(); System.out.print(minimumCountCharacterDeletionsfrequency(str.toCharArray(), length)); } }
Output:
2
Time Complexity: The time complexity of the program is O(N).
Space Complexity: The space complexity of the program is O(1).
Approach 3: Using Frequency Transformation Technique
ALGORITHM:
Step 1: Establish a frequency array called fre (of size 26 for each character) and store the frequency for each character in the provided string s. At index c-'a', we keep track of each character c's frequency.
Step 2: Set the count of characters that need to be deleted (cnt) to zero at initialization. Initiate a HashSet as well, which will hold the frequencies we have used.
Step 3: For every character, iterate over the characters from a to z as 0 to 25.
Step 3.1: Continue reducing the character's frequency until it is no longer visible, increasing the cnt with each decrease in frequency.
Step 3.2: Add the frequency to the set visible when it becomes unique, or zero.
Filename: FrequencyTransformation.java
import java.util.*; public class FrequencyTransformation { // A function to determine the least number of characters that must be removed in order for all character frequencies to be unique static int minimumCountCharacterDeletionsfrequency(char[] string, int length) { HashMapfrequencyMap = new HashMap (); int deletionCount = 0; // obtain the string's letter frequencies. for(char character: string) { if(!frequencyMap.containsKey(character)) { frequencyMap.put(character, 1); } else { frequencyMap.put(character, frequencyMap.get(character) + 1); } } // Put the frequencies in an arraylist for storage. ArrayList frequencies = new ArrayList<>( frequencyMap.values()); HashSet freqSet = new HashSet (); for(int value: frequencies) { if(!freqSet.contains(value)) { freqSet.add(value); } else { while(value > 0 && freqSet.contains(value)) { value--; deletionCount++; } freqSet.add(value); } } return deletionCount; } public static void main(String[] args) { String string = "aabbccdd"; int length = string.length(); System.out.print(minimumCountCharacterDeletionsfrequency(string.toCharArray(), length)); } }
Output:
5
Time Complexity: The time complexity of the program is O(N).
Space Complexity: The space complexity of the program is O(N).