DEV Community

Ganga Sri V
Ganga Sri V

Posted on

Majority Element

Problem Statement:
Given an array arr[]. Find the majority element in the array. If no majority element exists, return -1.

My Approach:

1.First I try to find a candidate the variable a for majority using a pattern.
2.I keep b to track how many times the candidate is supported.
3.If b becomes 0 then I pick the current number as a new candidate.
4.I increase b if the current number is the a else I decrease b.
5.After the one pass then I verify a by counting its total occurrences.
6.If it occurs more than n/2 times then I return it otherwise I return -1.

Methods Used:
Boyer-Moore Voting Algorithm

Top comments (0)