![]() |
VOOZH | about |
Given an array arr[] of size n, find the element that appears more than ⌊n/2⌋ times. If no such element exists, return -1.
Examples:
Input: arr[] = [1, 1, 2, 1, 3, 5, 1]
Output: 1
Explanation: Element 1 appears 4 times. Since ⌊7/2⌋ = 3, and 4 > 3, it is the majority element.Input: arr[] = [7]
Output: 7
Explanation: Element 7 appears once. Since ⌊1/2⌋ = 0, and 1 > 0, it is the majority element.Input: arr[] = [2, 13]
Output: -1
Explanation: No element appears more than ⌊2/2⌋ = 1 time, so there is no majority element.
Table of Content
The idea is to use nested loops to count frequencies. The outer loop selects each element as a candidate, and the inner loop counts how many times it appears. If any element appears more than n / 2 times, it is the majority element.
1
Note : We can also solve this problem by sorting and then doing a single traversal. This would solve the problem in O(n Log n) time. Another approach can be to count frequencies using hashing. This would work in linear time, but requires O(n) extra space. The below approach solves in linear time and constant extra space.
The algorithm is based on the idea that if an element occurs more than n/2 times, then all the remaining elements together must occur less than n/2 times.
While traversing the array, we maintain a candidate and a vote count:
0, it means the current candidate cannot be the majority element, so we select a new candidate.By the end of the first traversal, the remaining candidate is the potential majority element (if there is a majority element, then this elements has to be the one). A second traversal is required to verify whether it actually appears more than n/2 times.
There are mainly twos steps
Initialize candidate = -1 and count = 0.
Traverse the array:
== 0, set candidate = arr[i] and count = 1.arr[i] == candidate, increment count.count./2, return the candidate.-1.1