CA 21 - Find the Majority Element
Majority Element
Given an array arr[]. Find the majority element in the array. If no majority element exists, return -1.
Note: A majority element in an array is an element that appears strictly more than arr.size()/2 times in the array.
Input: arr[] = [1, 1, 2, 1, 3, 5, 1]
Output: 1
Explanation: Since, 1 is present more than 7/2 times, so it is the majority element.
Input: arr[] = [7]
Output: 7
Explanation: Since, 7 is single element and present more than 1/2 times, so it is the majority element.Input: arr[] = [2, 13]
Output: -1
Explanation: Since, no element is present more than 2/2 times, so there is no majority element. CODE:
Here we can solve the problem with the help of dictionary, if the frequency of the element is greater than length of array /2 then we will return it else we will return -1
class Solution:
def majorityElement(self, arr):
freq = {}
for num in arr:
freq[num] = freq.get(num, 0) + 1
if freq[num] > len(arr)//2:
return num
return -1
Comments
Post a Comment