A majority element in an array A[] of size n is an element that appears more than n/2 times
and hence there is at most one such element
[3 3 4 2 4 4 2 4 4] => 4
[3 3 4 2 4 4 2 4] => None
def findMajorityElement(arr):
dict = {}
for a in arr:
if a not in dict:
dict[a] = 0
dict[a] += 1
if dict[a] > (len(arr) / 2):
return a
return 'None'
arr = [3, 3, 4, 2, 4, 4, 2, 4, 4]
arr
[3, 3, 4, 2, 4, 4, 2, 4, 4]
findMajorityElement(arr)
4
arr = [3, 3, 4, 2, 4, 2, 4]
arr
[3, 3, 4, 2, 4, 2, 4]
findMajorityElement(arr)
'None'
This is a two step process.
Basic idea of the algorithm is if we cancel out each occurrence of an element e with all the other elements that are different from e then e will exist till end if it is a majority element
def chooseOne(arr):
chosen_index = 0
count = 1
for i in range(1, len(arr)):
if arr[chosen_index] == arr[i]:
count += 1
else:
count -= 1
if count == 0:
chosen_index = i
count = 1
return arr[chosen_index] if isMajority(arr, arr[chosen_index]) else 'None'
def isMajority(arr, chosenOne):
count = 0
for a in arr:
if chosenOne == a:
count += 1
if count > (len(arr) / 2):
return True
else:
return False
arr = [3, 3, 4, 2, 4, 4, 2, 4, 4]
arr
[3, 3, 4, 2, 4, 4, 2, 4, 4]
chooseOne(arr)
4
arr = [3, 3, 4, 2, 4, 2, 4]
arr
[3, 3, 4, 2, 4, 2, 4]
chooseOne(arr)
'None'