Majority Element in Python


Let’s suppose we have an array of integers. The task is to find the index of a particular element in the given array. For example,

Input-1

N = 8 A[ ] = { 1,2,4,3,3,1,1,5}

Output

1

Explanation − In the given array of integers, the most appearing number is ‘1’. Thus the output is ‘1’.

Input-2

N = 6 A[ ] = {1,5,4,4,1,1}

Output

1

Explanation − In the given array of integers, the most appearing number is ‘1’. Thus we can return the output ‘1’.

Approach to solve this problem

The given array contains multiple integers in which we have to find the most frequent element present in the array. To solve this problem in linear time O(n) and Linear Space O(n) we can use the approach of a hashmap.

In this approach, we will create an unordered map(STL Library) consist of key-value pair in which the key will be an element and the Value will be the occurrence of the element. While traversing through the map we will find the maximum occurrence of the number and return the number as Output.

  • Take Input an array of size N

  • An Integer function maxOccurrence(int A[], int size) takes an array and its size as an input and returns the numbers with maximum frequency.

  • Creating a hashmap of all the elements of the array by taking the key as an element and value as its frequency.

  • Iterating over the map and checking if any of the elements having the most frequency then return the result as the number. Otherwise, if there is not any number present in the array then return ‘-1’.

Example

 Live Demo

def checkMajorityElement(arr, N):
   mp = {}
   for i in range(0, N):
      if arr[i] in mp.keys():
         mp[arr[i]] += 1
      else:
         mp[arr[i]] = 1
   for key in mp:
      if mp[key] > (N / 2):
         return key
   return -1
print("Enter size of array:")
N = int(6)
print("Enter elements of array:")
arr = [2,1,1,2,2,2]
ans = checkMajorityElement(arr, N)
if ans != -1:
   print("Majority Element is: %d" % ans)
else:
   print("No majority element in array")

Output

Running the above code will generate the output as,

Enter size of array: 6
Enter elements of array: 2 1 1 2 2 2
Majority Element is: 2

Updated on: 05-Feb-2021

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements