find the kth least common element in an array in csharp

To find the kth least common element in an array in C#, we can use a combination of sorting and counting. We can sort the array and then loop through it, keeping track of the current element and the number of times it appears. Once we reach the kth least common element, we can return it.

Here's the code:

main.cs
public static int FindKthLeastCommon(int[] arr, int k)
{
    Array.Sort(arr);
    int count = 1;
    int current = arr[0];
    for (int i = 1; i < arr.Length; i++)
    {
        if (arr[i] == current)
        {
            count++;
        }
        else
        {
            if (count == k)
            {
                return current;
            }
            count = 1;
            current = arr[i];
        }
    }
    if (count == k)
    {
        return current;
    }
    throw new ArgumentException("k is greater than the number of unique elements in the array.");
}
578 chars
28 lines

This code assumes that the array has at least k unique elements. It first sorts the array and initializes variables to keep track of the current element and its count. It then loops through the array, incrementing the count when it encounters the current element and updating the current element when it encounters a new element. If the count reaches k, the method returns the current element. If the loop finishes without finding the kth least common element, an exception is thrown.

gistlibby LogSnag