VOOZH about

URL: https://www.geeksforgeeks.org/dsa/majority-element/

⇱ Majority Element - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Majority Element

Last Updated : 28 Mar, 2026

Given an array arr[] of size n, find the element that appears more than ⌊n/2⌋ times. If no such element exists, return -1.

Examples:

Input: arr[] = [1, 1, 2, 1, 3, 5, 1]
Output: 1
Explanation: Element 1 appears 4 times. Since ⌊7/2⌋ = 3, and 4 > 3, it is the majority element.

Input: arr[] = [7]
Output: 7
Explanation: Element 7 appears once. Since ⌊1/2⌋ = 0, and 1 > 0, it is the majority element.

Input: arr[] = [2, 13]
Output: -1
Explanation: No element appears more than ⌊2/2⌋ = 1 time, so there is no majority element.

[Naive Approach] Using Two Nested Loops - O(n^2) Time and O(1) Space

The idea is to use nested loops to count frequencies. The outer loop selects each element as a candidate, and the inner loop counts how many times it appears. If any element appears more than n / 2 times, it is the majority element.


Output
1

Note : We can also solve this problem by sorting and then doing a single traversal. This would solve the problem in O(n Log n) time. Another approach can be to count frequencies using hashing. This would work in linear time, but requires O(n) extra space. The below approach solves in linear time and constant extra space.

[Expected Approach] Using Moore's Voting Algorithm - O(n) Time and O(1) Space

The algorithm is based on the idea that if an element occurs more than n/2 times, then all the remaining elements together must occur less than n/2 times.

While traversing the array, we maintain a candidate and a vote count:

  • If the current element matches the candidate, we increment the vote count.
  • If it does not match, we decrement the vote count.
  • When the vote count becomes 0, it means the current candidate cannot be the majority element, so we select a new candidate.

By the end of the first traversal, the remaining candidate is the potential majority element (if there is a majority element, then this elements has to be the one). A second traversal is required to verify whether it actually appears more than n/2 times.

There are mainly twos steps

Step 1: Find a Candidate

Initialize candidate = -1 and count = 0.

Traverse the array:

  • If count == 0, set candidate = arr[i] and count = 1.
  • If arr[i] == candidate, increment count.
  • Otherwise, decrement count.

Step 2: Verify the Candidate

  • Count the occurrences of the candidate in the array.
  • If the count is greater than n/2, return the candidate.
  • Otherwise, return -1.

Output
1
Comment