| | | 1 | | // -------------------------------------------------------------------------------- |
| | | 2 | | // Copyright (C) 2026 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 sealed class MinimumDeletionsForKMostKDistinctCharactersFrequencyDictionaryBucketSort : |
| | | 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 frequencyDictionary = new Dictionary<char, int>(); |
| | | 28 | | |
| | 38 | 29 | | foreach (var c in s.Where(c => !frequencyDictionary.TryAdd(c, 1))) |
| | 5 | 30 | | { |
| | 5 | 31 | | frequencyDictionary[c]++; |
| | 5 | 32 | | } |
| | | 33 | | |
| | 4 | 34 | | if (frequencyDictionary.Count <= k) |
| | 1 | 35 | | { |
| | 1 | 36 | | return 0; |
| | | 37 | | } |
| | | 38 | | |
| | 12 | 39 | | var countToRemove = frequencyDictionary.Values.Count(frequency => frequency > 0) - k; |
| | | 40 | | |
| | 3 | 41 | | if (countToRemove <= 0) |
| | 0 | 42 | | { |
| | 0 | 43 | | return 0; |
| | | 44 | | } |
| | | 45 | | |
| | 3 | 46 | | var buckets = new int[s.Length]; |
| | | 47 | | |
| | 27 | 48 | | foreach (var frequency in frequencyDictionary) |
| | 9 | 49 | | { |
| | 9 | 50 | | buckets[frequency.Value - 1]++; |
| | 9 | 51 | | } |
| | | 52 | | |
| | 3 | 53 | | var result = 0; |
| | | 54 | | |
| | 14 | 55 | | for (var i = 0; i < s.Length && countToRemove > 0; i++) |
| | 4 | 56 | | { |
| | 9 | 57 | | while (buckets[i] > 0 && countToRemove > 0) |
| | 5 | 58 | | { |
| | 5 | 59 | | result += i + 1; |
| | | 60 | | |
| | 5 | 61 | | buckets[i]--; |
| | | 62 | | |
| | 5 | 63 | | countToRemove--; |
| | 5 | 64 | | } |
| | 4 | 65 | | } |
| | | 66 | | |
| | 3 | 67 | | return result; |
| | 4 | 68 | | } |
| | | 69 | | } |