find the kth most common element in an array in csharp

One way to find the kth most common element in an array in C# is by using a dictionary to count the occurrences of each element in the array, sorting the dictionary by the count in descending order, and then returning the kth element.

Here's an implementation:

main.cs
public static T FindKthMostCommonElement<T>(T[] array, int k)
{
    var counts = new Dictionary<T, int>();

    // count occurrences of each element
    foreach (var element in array)
    {
        if (counts.ContainsKey(element))
        {
            counts[element]++;
        }
        else
        {
            counts[element] = 1;
        }
    }

    // sort the dictionary by count in descending order
    var sortedCounts = counts.OrderByDescending(x => x.Value);

    // return the kth element
    return sortedCounts.ElementAt(k - 1).Key;
}
553 chars
24 lines

Here's how you can use this method:

main.cs
var array = new int[] { 1, 1, 2, 2, 2, 3, 3, 4, 4, 4, 4 };
var k = 2;

var kthMostCommonElement = FindKthMostCommonElement(array, k);

Console.WriteLine(kthMostCommonElement); // outputs 3
189 chars
7 lines

In this example, the second most common element in the array is 3, so the method returns 3.

gistlibby LogSnag