C# || How To Return The Top K Frequent Words In Array Of Strings Using C#
The following is a module with functions which demonstrates how to get the top K frequent words in an array of strings using C#.
1. Top K Frequent – Problem Statement
Given an array of strings words and an integer k, return the k most frequent strings.
Return the answer sorted by the frequency from highest to lowest. Sort the words with the same frequency by their lexicographical order.
Example 1:
Input: words = ["i","love","leetcode","i","love","coding"], k = 2
Output: ["i","love"]
Explanation: "i" and "love" are the two most frequent words.
Note that "i" comes before "love" due to a lower alphabetical order.
Example 2:
Input: words = ["the","day","is","sunny","the","the","the","sunny","is","is"], k = 4
Output: ["the","is","sunny","day"]
Explanation: "the", "is", "sunny" and "day" are the four most frequent words, with the number of occurrence being 4, 3, 2 and 1 respectively.
2. Top K Frequent – Solution
The following are two solutions which demonstrates how to get the top K frequent words in an array of strings.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
// ============================================================================ // Author: Kenneth Perkins // Date: Oct 23, 2022 // Taken From: http://programmingnotes.org/ // File: Solution.cs // Description: Determines how to get the top K frequent words in array // ============================================================================ public class Solution { public IList<string> TopKFrequent(string[] words, int k) { // Use a map to get the frequency of each word var frequency = new Dictionary<string, int>(); foreach (var word in words) { frequency[word] = frequency.GetValueOrDefault(word, 0) + 1; } // Get the frequency map as a list and sort var frequencyList = frequency.ToList(); frequencyList.Sort((a, b) => { // If words have the same frequency, sort // by their lexicographical order if (a.Value == b.Value) { return string.Compare(a.Key, b.Key); } // Sort by the frequency from highest to lowest return b.Value - a.Value; }); // Get the results var result = new List<string>(); for (int index = 0; index < frequencyList.Count; ++index) { result.Add(frequencyList[index].Key); if (result.Count == k) { break; } } return result; } }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
Once compiled, you should get this as your output for the example cases:
["i","love"]
["the","is","sunny","day"]
Leave a Reply