find the kth least frequent element in an array in csharp

One approach to find the kth least frequent element in an array involves using a dictionary to count the frequency of each element and sorting the results by frequency. This can be accomplished with the following code:

main.cs
public static int GetKthLeastFrequentElement(int[] arr, int k)
{
    var frequencyDict = new Dictionary<int, int>();
    foreach (var n in arr)
    {
        if (frequencyDict.ContainsKey(n))
        {
            frequencyDict[n]++;
        }
        else
        {
            frequencyDict[n] = 1;
        }
    }

    var sortedFrequencies = frequencyDict.OrderBy(x => x.Value).ToArray();
    if (k <= sortedFrequencies.Length)
    {
        return sortedFrequencies[k - 1].Key;
    }
    else
    {
        throw new ArgumentException("k is out of range");
    }
}
570 chars
26 lines

This code creates a dictionary to keep track of the frequency of each element in the array. It then sorts the dictionary by value (frequency) using LINQ's OrderBy method. Finally, it returns the kth element in the sorted array, which will be the kth least frequent element.

If the value of k is greater than the number of unique elements in the array, an ArgumentException is thrown.

gistlibby LogSnag