-3

I'm using python language. The clear algorithm will be enough for me.

I've tried using a dictionary, and counting the existence of each character if it is not in the list. But I'm not sure if it has the possible less complexity.

2 Answers2

0

Use the in built Counter(list).most_common(n) method, as below.

from collections import Counter

input_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 5, 7, 3, 1]

most_common_values = [value[0] for value in Counter(input_list).most_common(2)]

print(most_common_values)

This outputs: [1, 2].

The advantages to this approach are that it is fast, simple, and returns a list of the items in order. In addition, if their is a 'tie' in value count, it will return the example that appears first, as displayed in the example above.

KieranLock
  • 48
  • 1
  • 6
  • Please refer to this question for the time complexity of the `most_common(n)` method: https://stackoverflow.com/questions/29240807/python-collections-counter-most-common-complexity – KieranLock May 07 '21 at 12:52
-1

Use built-int Counter in collection library

Victor Ermakov
  • 471
  • 3
  • 6