Skip to content

Instantly share code, notes, and snippets.

@mandrewstuart
Created January 1, 2022 19:51
Show Gist options
  • Save mandrewstuart/ece25f6b15e2f1409418f4918dc252d1 to your computer and use it in GitHub Desktop.
Save mandrewstuart/ece25f6b15e2f1409418f4918dc252d1 to your computer and use it in GitHub Desktop.
# conversation from twitter: https://twitter.com/driscollis/status/1475571532898385927
# This function's worst case performance is n*log(n)
def find_most_common_number_in_list(number_list):
# O(n*log(n)))
counts = {}
for number in number_list:
try:
counts[number] += 1
except:
counts[number] = 1
# O(n)
sortable_list = [[item[1], item[0]] for item in counts.items()]
# O(n*log(n))
sortable_list.sort(reverse=True)
# O(1)
return sortable_list[0][1]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment