| | 1 | | // -------------------------------------------------------------------------------- |
| | 2 | | // Copyright (C) 2025 Eugene Eremeev (also known as Yevhenii Yeriemeieiv). |
| | 3 | | // All Rights Reserved. |
| | 4 | | // -------------------------------------------------------------------------------- |
| | 5 | | // This software is the confidential and proprietary information of Eugene Eremeev |
| | 6 | | // (also known as Yevhenii Yeriemeieiv) ("Confidential Information"). You shall not |
| | 7 | | // disclose such Confidential Information and shall use it only in accordance with |
| | 8 | | // the terms of the license agreement you entered into with Eugene Eremeev (also |
| | 9 | | // known as Yevhenii Yeriemeieiv). |
| | 10 | | // -------------------------------------------------------------------------------- |
| | 11 | |
|
| | 12 | | namespace LeetCode.Algorithms.MinimumDeletionsForKMostKDistinctCharacters; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class MinimumDeletionsForKMostKDistinctCharactersFrequencyArrayBucketSort : |
| | 16 | | IMinimumDeletionsForKMostKDistinctCharacters |
| | 17 | | { |
| | 18 | | /// <summary> |
| | 19 | | /// Time complexity - O(n) |
| | 20 | | /// Space complexity - O(n) |
| | 21 | | /// </summary> |
| | 22 | | /// <param name="s"></param> |
| | 23 | | /// <param name="k"></param> |
| | 24 | | /// <returns></returns> |
| | 25 | | public int MinDeletion(string s, int k) |
| 4 | 26 | | { |
| 4 | 27 | | var frequencyArray = new int['z' - 'a' + 1]; |
| | 28 | |
|
| 44 | 29 | | foreach (var c in s) |
| 16 | 30 | | { |
| 16 | 31 | | frequencyArray[c - 'a']++; |
| 16 | 32 | | } |
| | 33 | |
|
| 108 | 34 | | var countToRemove = frequencyArray.Count(frequency => frequency > 0) - k; |
| | 35 | |
|
| 4 | 36 | | if (countToRemove <= 0) |
| 1 | 37 | | { |
| 1 | 38 | | return 0; |
| | 39 | | } |
| | 40 | |
|
| 3 | 41 | | var buckets = new int[s.Length]; |
| | 42 | |
|
| 165 | 43 | | foreach (var frequency in frequencyArray) |
| 78 | 44 | | { |
| 78 | 45 | | if (frequency > 0) |
| 9 | 46 | | { |
| 9 | 47 | | buckets[frequency - 1]++; |
| 9 | 48 | | } |
| 78 | 49 | | } |
| | 50 | |
|
| 3 | 51 | | var result = 0; |
| | 52 | |
|
| 14 | 53 | | for (var i = 0; i < s.Length && countToRemove > 0; i++) |
| 4 | 54 | | { |
| 9 | 55 | | while (buckets[i] > 0 && countToRemove > 0) |
| 5 | 56 | | { |
| 5 | 57 | | result += i + 1; |
| | 58 | |
|
| 5 | 59 | | buckets[i]--; |
| | 60 | |
|
| 5 | 61 | | countToRemove--; |
| 5 | 62 | | } |
| 4 | 63 | | } |
| | 64 | |
|
| 3 | 65 | | return result; |
| 4 | 66 | | } |
| | 67 | | } |