How to find the Mode in Array C#? [duplicate]

Using nested loops is not a good way to solve this problem. It will have a run time of O(n^2) – much worse than the optimal O(n).

You can do it with LINQ by grouping identical values and then finding the group with the largest count:

int mode = x.GroupBy(v => v)
            .OrderByDescending(g => g.Count())
            .First()
            .Key;

This is both simpler and faster. But note that (unlike LINQ to SQL) LINQ to Objects currently doesn’t optimize the OrderByDescending when only the first result is needed. It fully sorts the entire result set which is an O(n log n) operation.

You might want this O(n) algorithm instead. It first iterates once through the groups to find the maximum count, and then once more to find the first corresponding key for that count:

var groups = x.GroupBy(v => v);
int maxCount = groups.Max(g => g.Count());
int mode = groups.First(g => g.Count() == maxCount).Key;

You could also use the MaxBy extension from MoreLINQ method to further improve the solution so that it only requires iterating through all elements once.

Leave a Comment