Find the element that appears more than n/2 times in an array. Such an element is guaranteed to exist.
Input
Line 1: an integer n.
Line 2: n integers.
Output
The majority element.
Find the element that appears more than n/2 times in an array. Such an element is guaranteed to exist.
Line 1: an integer n.
Line 2: n integers.
The majority element.
Example 1
3 3 2 3
3
3 appears twice of three — a majority.
Example 2
7 2 2 1 1 1 2 2
2
2 appears four of seven times.
Example 3
1 5
5
The only element is the majority.
Counting every value works, but there is a clever O(1)-space way.
Boyer–Moore voting: keep a candidate and a counter; on a match increment, otherwise decrement, and reset the candidate when the counter hits 0.
Boyer–Moore majority vote: because the majority element outnumbers all others combined, its net vote survives.
import sys
d = list(map(int, sys.stdin.read().split()))
n = d[0]
a = d[1:1 + n]
cand = None
cnt = 0
for x in a:
if cnt == 0:
cand = x
cnt += 1 if x == cand else -1
print(cand)
Tell us what needs to change, who it affects and any important deadline. We will review the context and reply with useful next questions.