|
| 1 | +LeetCode 3085 – Minimum Deletions to Make String K-Special |
| 2 | + |
| 3 | +class Solution { |
| 4 | + public int minimumDeletions(String word, int k) { |
| 5 | + int[] freq = new int[26]; |
| 6 | + |
| 7 | + for (char c : word.toCharArray()) { |
| 8 | + freq[c - 'a']++; |
| 9 | + } |
| 10 | + |
| 11 | + Arrays.sort(freq); |
| 12 | + int res = Integer.MAX_VALUE; |
| 13 | + |
| 14 | + for (int i = 0; i < 26; i++) { |
| 15 | + if (freq[i] == 0) continue; |
| 16 | + |
| 17 | + int del = 0; |
| 18 | + for (int j = 0; j < 26; j++) { |
| 19 | + if (freq[j] == 0) continue; |
| 20 | + if (freq[j] < freq[i]) { |
| 21 | + del += freq[j]; // delete all smaller |
| 22 | + } else if (freq[j] - freq[i] > k) { |
| 23 | + del += freq[j] - (freq[i] + k); // reduce excess |
| 24 | + } |
| 25 | + } |
| 26 | + |
| 27 | + res = Math.min(res, del); |
| 28 | + } |
| 29 | + |
| 30 | + return res; |
| 31 | + } |
| 32 | +} |
| 33 | + |
| 34 | +Explanation |
| 35 | + |
| 36 | +int[] freq = new int[26]; |
| 37 | +🔹 26 lowercase letters ke frequency count karne ke liye array. |
| 38 | + |
| 39 | +for (char c : word.toCharArray()) |
| 40 | +🔹 Har character ki frequency count kar li. |
| 41 | + |
| 42 | +Arrays.sort(freq); |
| 43 | +🔹 Frequency array ko sort kar diya → smallest to largest. |
| 44 | + |
| 45 | +int res = Integer.MAX_VALUE; |
| 46 | +🔹 Minimum deletions store karne ke liye variable. |
| 47 | + |
| 48 | +for (int i = 0; i < 26; i++) |
| 49 | +🔹 Har possible freq[i] ke liye assume kar rahe hain usse as minimum freq. |
| 50 | + |
| 51 | +if (freq[i] == 0) continue; |
| 52 | +🔹 Agar koi character nahi mila toh skip. |
| 53 | + |
| 54 | +int del = 0; |
| 55 | +🔹 Deletions count karne ke liye variable. |
| 56 | + |
| 57 | +for (int j = 0; j < 26; j++) |
| 58 | +🔹 Har character ke liye check karenge ki freq[i] ke according adjust karna hai ya delete karna hai. |
| 59 | + |
| 60 | +if (freq[j] == 0) continue; |
| 61 | +🔹 Agar koi character nahi hai toh skip. |
| 62 | + |
| 63 | +if (freq[j] < freq[i]) |
| 64 | +🔹 Agar freq[i] se chhota hai toh pura delete kar do. |
| 65 | + |
| 66 | +else if (freq[j] - freq[i] > k) |
| 67 | +🔹 Agar allowed difference (k) se zyada hai toh extra occurrences delete karo. |
| 68 | + |
| 69 | +res = Math.min(res, del); |
| 70 | +🔹 Minimum deletions update karo. |
| 71 | + |
| 72 | +return res; |
| 73 | +🔹 Final answer return karo. |
| 74 | + |
| 75 | +Example: |
| 76 | +Input: word = "aabcabb", k = 1 |
| 77 | +Frequencies: a=3, b=3, c=1 |
| 78 | + |
| 79 | +→ To make all freq difference <= k, |
| 80 | +Delete 'c' → only 1 deletion needed. |
| 81 | + |
| 82 | +Output: 1 |
| 83 | +Time and Space Complexity: |
| 84 | +Item Complexity |
| 85 | +Time O(26²) = O(1) practically (constant) |
| 86 | +Space O(26) = O(1) |
| 87 | + |
| 88 | +🔗 Need more help or Java tricks? |
| 89 | +https://www.linkedin.com/in/saurabh884095/ |
0 commit comments