Challenges • Asked over 4 years ago by abrar
the solution mentinons sorting (O(nlogn)).
instead we can use dictionary/hashmap
sorting in O(n), n = number of elements
searching for majority element O(m) at worst case, m = number of keys of dictionary
where m < n
overall we are doing it in O(n), linear time
`def majorityelement(nums):
n = len(nums)/2
countdict = {}
# set item count to dict
for item in nums:
countdict[item] = countdict.get(item, 0) + 1
# count the number of occurances
for key in countdict.keys():
if countdict[key] > n:
return key`
Link to problem: Majority Element.