Majority Element | Set-2 (Hashing)

Given an array of size N, find the majority element. The majority element is the element that appears more than \floor{\frac{n}{2}} times in the given array.

Examples:

Input: [3, 2, 3]
Output: 3

Input: [2, 2, 1, 1, 1, 2, 2]
Output: 2

The problem has been solved using 4 different methods in the previous post. In this post hashing based solution is implemented. We count occurrences of all elements. And if count of any element becomes more than n/2, we return it.

Hence if there is a majority-element, it will be the value of the key.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

#include<bits/stdc++.h>
using namespace std;
  
#define ll long long int
  
// function to print the majority Number
int majorityNumber(int arr[], int n)
{
    int ans = -1;
    unordered_map<int, int>freq;
    for (int i = 0; i < n; i++)
    {
        freq[arr[i]]++;
        if (freq[arr[i]] > n / 2)
            ans = arr[i];
    }
    return ans;
  
// Driver code
int main()
{
    int a[] = {2, 2, 1, 1, 1, 2, 2};
    int n = sizeof(a) / sizeof(int);
    cout << majorityNumber(a, n); 
    return 0;
}
  
// This code is contributed 
// by sahishelangia

chevron_right


Python

filter_none

edit
close

play_arrow

link
brightness_4
code

# function to print the 
# majorityNumber
def majorityNumber(nums):
      
    # stores the key count 
    key, count = None, 0
      
    # iterate in the array 
    for num in nums:
          
        # key is 0
        if key is None:
            key, count = num, 1
        else:
            if key == num:
                count += 1
            else:
                count -= 1
  
        if count == 0:
            key = None
  
    return key
  
# Driver Code
a = [2, 2, 1, 1, 1, 2, 2]
print majorityNumber(a)

chevron_right


Output:

2

Below is the time and space complexity of the above algorithm:-

Time Complexity : O(n)
Auxiliary Space : O(n)



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.