# Given a sorted array, find the element that appears the most
# There are many ways to do this, brute force way is to loop twice -> O(n^2)
def majorityElement(arr):
maxCount = 0
element = None
for i in range(len(arr)):
if arr[i] == element:
continue
count = 0
for j in range(i,len(arr)):
if arr[i] == arr[j]:
count += 1
if maxCount < count:
maxCount = count
element = arr[i]
return [element, maxCount]
# Another way is to loop once but keep a dictionary of count
# This has a time complexity of O(n) and space complexity of O(n) as well
def majorityElement2(arr):
map = {}
for x in arr:
if x in map:
map[x] += 1
else:
map[x] = 1
count = 0
element = None
for key, value in map.items():
if count < value:
count = value
element = key
return [element, count]
# This is the preferred solution with time complexity of O(n) but space complexity of O(1)
def majorityElement3(arr):
maxCount = 0
element = arr[0]
elementIndex = 0
count = 1
for i in range(1, len(arr)):
if arr[i] == element:
count += 1
else:
if maxCount < count:
maxCount = count
elementIndex = i - 1
element = arr[i]
count = 1
return [arr[elementIndex], maxCount]
if __name__ == '__main__':
arr = list(map(int, input().strip().split(' ')))
[element, count] = majorityElement3(arr)
print("The majority element is", element, "with a count of ", count)