mostCommon method

T mostCommon()

Returns the most common element in the iterable.

Two elements are considered the same if they are equal.

If there are ties for the most common element, the latest most common element will be returned.

If the iterable is empty, this method will throw.

This method has O(n) space and time complexity, where n is the number of elements.

Implementation

T mostCommon() {
  if (isEmpty) {
    throw StateError('No elements');
  }

  final counts = <T, int>{};
  MapEntry<T, int>? best;

  for (final element in this) {
    var count = counts[element] ?? 0;
    count++;

    counts[element] = count;

    if (best == null || count >= best.value) {
      best = MapEntry(element, count);
    }
  }

  return best!.key;
}