-4

I want to use System.Linq for writing a method that returns the first, most frequent character in a string. eg: "AABABBC" => 'A'. If two letters occur the same, the first one that appears in the string should be returned.

The sample below should work. However, I'm trying to find a more efficient solution, which doesn't imply sorting the characters first. I was thinking of using Enumerable.Aggregate() for counting the repetitions while also iterating through the word. Not sure how to to that, though... Any ideas? Thanks :)

    public static char MostAparitionsChar(string word)
    {
       return word.GroupBy(x => x)
            .OrderByDescending(x => x.Count())
            .Select(g => g.Key)
            .First();  
    }

1 Answers1

0

I don't know the exact implementation of OrderByDescending, but I assume it is not faster than O(n*log n). But finding a maximum value should only be O(n). Hence you can save some time if you don't sort, but only look for the maximum:

public static char MostAparitionsChar(string word)
 {
 char result = ' ';
 int max = int.MinValue;
 foreach(var grouping in word.GroupBy(x => x))
  {
  int count = grouping.Count();
  if(count > max)
   {
   max = count;
   result = grouping.Key;
  }
 }
 return result;
}
SomeBody
  • 7,515
  • 2
  • 17
  • 33
  • Note that this only applies to .NET Framework. .NET Core already has an optimization for `OrderBy(...).First()` – canton7 Oct 08 '19 at 09:52