How to find all of the most common elements in a python list (order alphabetically in case of tie)?
Here is a possible solution (as discussed in the comments):
from collections import Counter
lst = # your list of characters
c = Counter(lst) # O(n)
largest = max(counts.values()) # O(n)
largest_with_ties = [k for k, v in counts.items() if v == largest] # O(n)
result = sorted(largest_with_ties)
Now, what's the complexity of sorted(largest_with_ties)
? One could say that it's O(nlogn) (because there could be n/2 ties). However, the number of characters in largest_with_ties
cannot be as large as the number of elements in lst
. And that's because there is a much smaller number of characters compared to the possible number of ints. In other words, lst
could potentially contain 10^20 numbers (just an example). But largest_with_ties
can only contain different characters, and the number of characters that can be represented (for example) with UTF8 is limited to more or less 10^6. Therefore, technically the complexity of this last operation is O(1). In general, we could say that it's O(nlogn) but with an upper limit of O(10^6log10^6).