![]() |
VOOZH | about |
Given a sorted array arr[] of size n, find if there is a majority element in the array or not. An element is called a majority element if it appears more than n/2 times in the array.
Examples:
Input: arr[] = [1, 2, 3, 3, 3, 3, 10]
Output: true
Explanation: 3 is majority in the arrayInput: arr[] = [1, 1, 2, 4, 4, 4, 6, 6]
Output: false
Explanation: There is no majority in the array.
Table of Content
The idea is based on the property that if there is a majority in a sorted array, then it must be present at the mid index. So, we first take the middle element arr[n/2] and count how many times it appears in the array. If its count is greater than n/2, then it is a majority element; otherwise, it is not.
true
We first take the middle element x = arr[n/2] and use Binary Search to find its first occurrence. Let the first occurrence index be i. If x is a majority element, then the element at index i + n/2 must also be equal to x. Otherwise, x cannot appear more than n/2 times.
Consider: arr[] = [1, 2, 3, 3, 3, 3, 10]
Middle element: x = arr[7/2] = arr[3] = 3
Step 1: Find First Occurrence of x
Initial range: low = 0, high = 3
Iteration 1
Iteration 2
Step 2: Check Majority Condition
Final Result: true
true