Given an array of size N, find the majority element. The majority element is the element that appears more than times in the given array.
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:
Below is the time and space complexity of the above algorithm:-
Time Complexity : O(n)
Auxiliary Space : O(n)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Check for Majority Element in a sorted array
- Find the Majority Element | Set 3 (Bit Magic)
- Check if an array has a majority element
- Majority element in a linked list
- Count majority element in a matrix
- Majority element in a circular array of 0's and 1's
- Majority Element
- Convert an array to reduced form | Set 1 (Simple and Hashing)
- Cuckoo Hashing - Worst case O(1) Lookup!
- Top 20 Hashing Technique based Interview Questions
- Hashing | Set 1 (Introduction)
- Hashing | Set 2 (Separate Chaining)
- Union and Intersection of two linked lists | Set-3 (Hashing)
- Index Mapping (or Trivial Hashing) with negatives allowed
- Practice Problems on Hashing
- C++ program for hashing with chaining
- Double Hashing
- Coalesced hashing
- Applications of Hashing
- Hashing in Java
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.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.