Skip to content

Instantly share code, notes, and snippets.

@Kavignon
Created October 7, 2021 01:19
Show Gist options
  • Save Kavignon/ced990c8b1469ad6172da42ff9916e36 to your computer and use it in GitHub Desktop.
Save Kavignon/ced990c8b1469ad6172da42ff9916e36 to your computer and use it in GitHub Desktop.
Implementation for the LeetCode problem 'Top K frequent words' solved with an hash table and min-heap
public class Solution
{
public IList<string> TopKFrequent(string[] words, int k) {
var output = new string[k];
if (words == null || words.Length == 0)
{
return output;
}
var wordFrequencyMap = new Dictionary<string, int>();
foreach (string word in words)
{
if (wordFrequencyMap.ContainsKey(word))
{
wordFrequencyMap[word]++;
}
else
{
wordFrequencyMap.Add(word, 1);
}
}
var heap = new SortedSet<(int frequency, string word)>(new WordFrequencyComparer());
foreach (var pair in wordFrequencyMap)
{
heap.Add((pair.Value * -1, pair.Key));
}
int idx = 0;
foreach (var pair in heap)
{
if (idx == k)
{
break;
}
output[idx] = pair.word;
idx++;
}
return output;
}
}
public class WordFrequencyComparer : IComparer<(int frequency, string word)>
{
public int Compare((int frequency, string word) firstWordFrequency, (int frequency, string word) secondWordFrequency)
{
if (firstWordFrequency.frequency == secondWordFrequency.frequency)
{
return firstWordFrequency.word.CompareTo(secondWordFrequency.word);
}
return firstWordFrequency.frequency - secondWordFrequency.frequency;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment