Approach:
Step 1 Take the array
Step 2 Use count and candidate
Step 3 If count becomes 0 update candidate
Step 4 Increase or decrease count
Step 5 Verify candidate
Why this works???
Majority element survives cancellation
other elements cancel each other
remaining is possible answer
Code:
def majorityElement(arr):
c=None
count=0
for x in arr:
if count==0:
c=x
if x==c:
count+=1
else:
count-=1
if arr.count(c)>len(arr)//2:
return c
return-1
Limitation:
Requires second pass for verification
Top comments (0)