Python3 Program for Check for Majority Element in a sorted array
Last Updated :
06 Sep, 2024
Question: Write a function to find if a given integer x appears more than n/2 times in a sorted array of n integers.
Basically, we need to write a function say isMajority() that takes an array (arr[] ), array’s size (n) and a number to be searched (x) as parameters and returns true if x is a majority element (present more than n/2 times).
Examples:
Input: arr[] = {1, 2, 3, 3, 3, 3, 10}, x = 3
Output: True (x appears more than n/2 times in the given array)
Input: arr[] = {1, 1, 2, 4, 4, 4, 6, 6}, x = 4
Output: False (x doesn't appear more than n/2 times in the given array)
Input: arr[] = {1, 1, 1, 2, 2}, x = 1
Output: True (x appears more than n/2 times in the given array)
METHOD 1 (Using Linear Search)
Linearly search for the first occurrence of the element, once you find it (let at index i), check element at index i + n/2. If element is present at i+n/2 then return 1 else return 0.
Python
'''Python3 Program to check for majority element in a sorted array'''
def isMajority(arr, n, x):
# get last index according to n (even or odd) */
last_index = (n//2 + 1) if n % 2 == 0 else (n//2)
# search for first occurrence of x in arr[]*/
for i in range(last_index):
# check if x is present and is present more than n / 2 times */
if arr[i] == x and arr[i + n//2] == x:
return 1
# Driver program to check above function */
arr = [1, 2, 3, 4, 4, 4, 4]
n = len(arr)
x = 4
if (isMajority(arr, n, x)):
print ("% d appears more than % d times in arr[]"
%(x, n//2))
else:
print ("% d does not appear more than % d times in arr[]"
%(x, n//2))
# This code is contributed by shreyanshi_arun.
Output 4 does not appear more than 3 times in arr[]
Time Complexity: O(n)
Auxiliary Space: O(1)
METHOD 2 (Using Binary Search)
Use binary search methodology to find the first occurrence of the given number. The criteria for binary search is important here.
Python
'''Python3 Program to check for majority element in a sorted array'''
# This function returns true if the x is present more than n / 2
# times in arr[] of size n */
def isMajority(arr, n, x):
# Find the index of first occurrence of x in arr[] */
i = _binarySearch(arr, 0, n-1, x)
# If element is not present at all, return false*/
if i == -1:
return False
# check if the element is present more than n / 2 times */
if ((i + n//2) <= (n -1)) and arr[i + n//2] == x:
return True
else:
return False
# If x is present in arr[low...high] then returns the index of
# first occurrence of x, otherwise returns -1 */
def _binarySearch(arr, low, high, x):
if high >= low:
mid = (low + high)//2 # low + (high - low)//2;
''' Check if arr[mid] is the first occurrence of x.
arr[mid] is first occurrence if x is one of the following
is true:
(i) mid == 0 and arr[mid] == x
(ii) arr[mid-1] < x and arr[mid] == x'''
if (mid == 0 or x > arr[mid-1]) and (arr[mid] == x):
return mid
elif x > arr[mid]:
return _binarySearch(arr, (mid + 1), high, x)
else:
return _binarySearch(arr, low, (mid -1), x)
return -1
# Driver program to check above functions */
arr = [1, 2, 3, 3, 3, 3, 10]
n = len(arr)
x = 3
if (isMajority(arr, n, x)):
print ("% d appears more than % d times in arr[]"
% (x, n//2))
else:
print ("% d does not appear more than % d times in arr[]"
% (x, n//2))
# This code is contributed by shreyanshi_arun.
Output 3 appears more than 3 times in arr[]
Time Complexity: O(Log n)
Auxiliary Space: O(1)
METHOD 3: If it is already given that the array is sorted and there exists a majority element, checking if a particular element is as easy as checking if the middle element of the array is the number we are checking against.
Since a majority element occurs more than n/2 times in an array, it will always be the middle element. We can use this logic to check if the given number is the majority element.
Python
def isMajorityElement(arr,
n, key):
if (arr[n // 2] == key):
return True
return False
# Driver code
if __name__ == "__main__":
arr = [1, 2, 3, 3,
3, 3, 10]
n = len(arr)
x = 3
if (isMajorityElement(arr, n, x)):
print(x, " appears more than ",
n // 2 , " times in arr[]")
else:
print(x, " does not appear more than",
n // 2, " times in arr[]")
# This code is contributed by Chitranayal
Output3 appears more than 3 times in arr[]
Time Complexity: O(1)
Auxiliary Space: O(1)
Please refer complete article on Check for Majority Element in a sorted array for more details!
Using Binary Search:
Approach:
Since the array is sorted, we can perform a binary search to find the first occurrence and last occurrence of the given element. Then we can check if the count of occurrences is greater than n/2.
Define a binary_search function that takes the sorted array arr, the element to be searched x, and a boolean value search_first indicating whether to search for the first occurrence or the last occurrence of x in arr.
Initialize low and high as the first and last indices of arr.
Initialize a variable result to -1 to keep track of the index of the first or last occurrence of x.
Use a while loop to perform binary search on arr until low becomes greater than high.
In each iteration of the loop, calculate the mid index as the average of low and high.
If the element at index mid is equal to x, then set result to mid and update low and high based on the value of search_first.
If the element at index mid is less than x, then set low to mid + 1.
If the element at index mid is greater than x, then set high to mid - 1.
Return the value of result.
In the is_majority_element function, use binary_search to find the first and last occurrences of x in arr.
Calculate the count of occurrences of x as last_index - first_index + 1.
If the count is greater than len(arr) / 2, then return True indicating that x is the majority element. Otherwise, return False.
Python
def binary_search(arr, x, search_first):
low = 0
high = len(arr) - 1
result = -1
while low <= high:
mid = (low + high) // 2
if arr[mid] == x:
result = mid
if search_first:
high = mid - 1
else:
low = mid + 1
elif arr[mid] < x:
low = mid + 1
else:
high = mid - 1
return result
def is_majority_element(arr, x):
first_index = binary_search(arr, x, True)
last_index = binary_search(arr, x, False)
count = last_index - first_index + 1
if count > len(arr) / 2:
return True
else:
return False
arr1 = [1, 2, 3, 3, 3, 3, 10]
x1 = 3
print(is_majority_element(arr1, x1)) # Output: True
arr2 = [1, 1, 2, 4, 4, 4, 6, 6]
x2 = 4
print(is_majority_element(arr2, x2)) # Output: False
arr3 = [1, 1, 1, 2, 2]
x3 = 1
print(is_majority_element(arr3, x3)) # Output: True
Time Complexity: O(log n)
Auxiliary Space: O(1)
Similar Reads
Python3 Program for Ceiling in a sorted array
Given a sorted array and a value x, the ceiling of x is the smallest element in array greater than or equal to x, and the floor is the greatest element smaller than or equal to x. Assume that the array is sorted in non-decreasing order. Write efficient functions to find floor and ceiling of x. Examp
4 min read
Python Program for Least frequent element in an array
Given an array, find the least frequent element in it. If there are multiple elements that appear least number of times, print any one of them.Examples : Input : arr[] = {1, 3, 2, 1, 2, 2, 3, 1} Output : 3 3 appears minimum number of times in given array. Input : arr[] = {10, 20, 30} Output : 10 or
3 min read
Python3 Program for Check if an array is sorted and rotated
Given an array of N distinct integers. The task is to write a program to check if this array is sorted and rotated counter-clockwise. A sorted array is not considered as sorted and rotated, i.e., there should at least one rotation.Examples: Input : arr[] = { 3, 4, 5, 1, 2 }Output : YESThe above arra
3 min read
Python3 Program to Find lost element from a duplicated array
Given two arrays that are duplicates of each other except one element, that is one element from one of the array is missing, we need to find that missing element.Examples: Input: arr1[] = {1, 4, 5, 7, 9} arr2[] = {4, 5, 7, 9}Output: 11 is missing from second array.Input: arr1[] = {2, 3, 4, 5} arr2[]
4 min read
Python3 Program for Search an element in a sorted and rotated array
An element in a sorted array can be found in O(log n) time via binary search. But suppose we rotate an ascending order sorted array at some pivot unknown to you beforehand. So for instance, 1 2 3 4 5 might become 3 4 5 1 2. Devise a way to find an element in the rotated array in O(log n) time. Examp
8 min read
Python3 Program for Range Queries for Frequencies of array elements
Given an array of n non-negative integers. The task is to find frequency of a particular element in the arbitrary range of array[]. The range is given as positions (not 0 based indexes) in array. There can be multiple queries of given type. Examples: Input : arr[] = {2, 8, 6, 9, 8, 6, 8, 2, 11}; lef
4 min read
Python Program to check if given array is Monotonic
Given an array A containing n integers. The task is to check whether the array is Monotonic or not. An array is monotonic if it is either monotone increasing or monotone decreasing. An array A is monotone increasing if for all i <= j, A[i] <= A[j]. An array A is monotone decreasing if for all
7 min read
Python program to insert an element into sorted list
Inserting an element into a sorted list while maintaining the order is a common task in Python. It can be efficiently performed using built-in methods or custom logic. In this article, we will explore different approaches to achieve this.Using bisect.insort bisect module provides the insort function
2 min read
Python Program to Print uncommon elements from two sorted arrays
Given two sorted arrays of distinct elements, we need to print those elements from both arrays that are not common. The output should be printed in sorted order. Examples : Input : arr1[] = {10, 20, 30} arr2[] = {20, 25, 30, 40, 50} Output : 10 25 40 50 We do not print 20 and 30 as these elements ar
3 min read
Python - Check if all elements in List are same
To check if all items in list are same, we have multiple methods available in Python. Using SetUsing set() is the best method to check if all items are same in list. Pythona = [3, 3, 3, 3] # Check if all elements are the same result = len(set(a)) == 1 print(result) OutputTrue Explanation:Converting
3 min read