Arrays January 13 ,2026

Find the Majority Element (Moore’s Voting Algorithm)

Problem Statement

You are given an array of integers of size n.
A majority element is an element that appears more than ⌊n / 2⌋ times in the array.

You need to find and return the majority element.

Assumption: The majority element always exists.

Example 1

Input

arr = [3, 2, 3]

Output

3

Example 2

Input

arr = [2, 2, 1, 1, 1, 2, 2]

Output

2

Why This Problem Is Important

  • Extremely common interview question
  • Tests array traversal and frequency logic
  • Introduces cancellation principle
  • Foundation for optimized frequency problems
  • Leads to Moore’s Voting Algorithm

Approaches Overview

ApproachTechniqueTimeSpace
Approach 1Brute ForceO(n²)O(1)
Approach 2Hash Map / Frequency CountO(n)O(n)
Approach 3Moore’s Voting AlgorithmO(n)O(1)

Approach 1: Brute Force

Idea

For each element, count how many times it appears in the array.
If the count exceeds n/2, that element is the majority element.

Algorithm

  1. Loop through each element i
  2. Initialize count = 0
  3. Loop again to count occurrences of arr[i]
  4. If count > n/2, return arr[i]

Time & Space Complexity

  • Time: O(n²)
  • Space: O(1)

Implementations

C

#include 

int main() {
    int arr[] = {2,2,1,1,1,2,2};
    int n = 7;

    for(int i = 0; i < n; i++) {
        int count = 0;
        for(int j = 0; j < n; j++) {
            if(arr[i] == arr[j])
                count++;
        }
        if(count > n/2) {
            printf("%d", arr[i]);
            break;
        }
    }
    return 0;
}

C++

#include 
using namespace std;

int main() {
    int arr[] = {2,2,1,1,1,2,2};
    int n = 7;

    for(int i = 0; i < n; i++) {
        int count = 0;
        for(int j = 0; j < n; j++) {
            if(arr[i] == arr[j])
                count++;
        }
        if(count > n/2) {
            cout << arr[i];
            break;
        }
    }
    return 0;
}

Java

public class MajorityElement {
    public static void main(String[] args) {
        int[] arr = {2,2,1,1,1,2,2};
        int n = arr.length;

        for(int i = 0; i < n; i++) {
            int count = 0;
            for(int j = 0; j < n; j++) {
                if(arr[i] == arr[j])
                    count++;
            }
            if(count > n/2) {
                System.out.print(arr[i]);
                break;
            }
        }
    }
}

Python

arr = [2,2,1,1,1,2,2]
n = len(arr)

for i in range(n):
    count = 0
    for j in range(n):
        if arr[i] == arr[j]:
            count += 1
    if count > n//2:
        print(arr[i])
        break

JavaScript

let arr = [2,2,1,1,1,2,2];
let n = arr.length;

for (let i = 0; i < n; i++) {
    let count = 0;
    for (let j = 0; j < n; j++) {
        if (arr[i] === arr[j])
            count++;
    }
    if (count > Math.floor(n / 2)) {
        console.log(arr[i]);
        break;
    }
}

Approach 2: Hash Map / Frequency Count

Idea

Store frequency of each element using a map.
Return the element whose frequency exceeds n/2.

Algorithm

  1. Create an empty map
  2. Traverse the array
  3. Increment frequency of each element
  4. If frequency > n/2, return the element

Time & Space Complexity

  • Time: O(n)
  • Space: O(n)

Implementations

C++

#include 
#include 
using namespace std;

int main() {
    int arr[] = {2,2,1,1,1,2,2};
    int n = 7;
    unordered_map freq;

    for(int i = 0; i < n; i++) {
        freq[arr[i]]++;
        if(freq[arr[i]] > n/2) {
            cout << arr[i];
            break;
        }
    }
    return 0;
}

Java

import java.util.HashMap;

public class MajorityElement {
    public static void main(String[] args) {
        int[] arr = {2,2,1,1,1,2,2};
        HashMap map = new HashMap<>();

        for(int num : arr) {
            map.put(num, map.getOrDefault(num, 0) + 1);
            if(map.get(num) > arr.length / 2) {
                System.out.print(num);
                break;
            }
        }
    }
}

Python

arr = [2,2,1,1,1,2,2]
freq = {}

for num in arr:
    freq[num] = freq.get(num, 0) + 1
    if freq[num] > len(arr)//2:
        print(num)
        break

JavaScript

let arr = [2,2,1,1,1,2,2];
let freq = {};

for (let num of arr) {
    freq[num] = (freq[num] || 0) + 1;
    if (freq[num] > Math.floor(arr.length / 2)) {
        console.log(num);
        break;
    }
}

Approach 3: Moore’s Voting Algorithm (Optimal)

Idea

If an element appears more than n/2 times, it will never be fully cancelled out by other elements.

Maintain:

  • candidate
  • count
🧠 Understanding the Boyer-Moore Voting Algorithm: A Clever Approach to  Finding the Majority Element | by Ddhankhar | Medium

Algorithm

  1. Initialize count = 0, candidate = None
  2. Traverse the array
    • If count == 0, set candidate = current element
    • If current element == candidate → count++
    • Else → count--
  3. candidate will be the majority element

Time & Space Complexity

  • Time: O(n)
  • Space: O(1)

Implementations

C

#include 

int main() {
    int arr[] = {2,2,1,1,1,2,2};
    int n = 7;
    int count = 0, candidate = 0;

    for(int i = 0; i < n; i++) {
        if(count == 0)
            candidate = arr[i];

        if(arr[i] == candidate)
            count++;
        else
            count--;
    }

    printf("%d", candidate);
    return 0;
}

C++

#include 
using namespace std;

int main() {
    int arr[] = {2,2,1,1,1,2,2};
    int count = 0, candidate = 0;

    for(int num : arr) {
        if(count == 0)
            candidate = num;

        if(num == candidate)
            count++;
        else
            count--;
    }

    cout << candidate;
    return 0;
}

Java

public class MajorityElement {
    public static void main(String[] args) {
        int[] arr = {2,2,1,1,1,2,2};
        int count = 0, candidate = 0;

        for(int num : arr) {
            if(count == 0)
                candidate = num;

            if(num == candidate)
                count++;
            else
                count--;
        }

        System.out.print(candidate);
    }
}

Python

arr = [2,2,1,1,1,2,2]
count = 0
candidate = None

for num in arr:
    if count == 0:
        candidate = num
    count += 1 if num == candidate else -1

print(candidate)

JavaScript

let arr = [2,2,1,1,1,2,2];
let count = 0, candidate = null;

for (let num of arr) {
    if (count === 0) candidate = num;
    count += (num === candidate) ? 1 : -1;
}

console.log(candidate);

Dry Run (Moore’s Voting Algorithm)

Input

[2, 2, 1, 1, 1, 2, 2]
ElementCandidateCount
221
222
121
120
111
210
221

Final Answer

2

Summary

  • Brute force is simple but inefficient
  • Hash map improves time but uses extra space
  • Moore’s Voting Algorithm is optimal and interview-preferred
  • Solves the problem in one pass with constant space

Next Problem in the Series

Find All Pairs with Given Sum


 

Sanjiv
0

You must logged in to post comments.

Related Blogs

Find the S...
Arrays February 02 ,2026

Find the Second Smal...

Find the S...
Arrays January 01 ,2026

Find the Sum of All...

Find the M...
Arrays January 01 ,2026

Find the Maximum Ele...

Find the M...
Arrays January 01 ,2026

Find the Minimum Ele...

Count Even...
Arrays January 01 ,2026

Count Even and Odd N...

Search an...
Arrays January 01 ,2026

Search an Element in...

Copy One A...
Arrays January 01 ,2026

Copy One Array into...

Reverse an...
Arrays January 01 ,2026

Reverse an Array

Print Alte...
Arrays January 01 ,2026

Print Alternate Elem...

Find the L...
Arrays January 01 ,2026

Find the Length of a...

Check if a...
Arrays January 01 ,2026

Check if an Array is...

Find the F...
Arrays January 01 ,2026

Find the First Eleme...

Find the L...
Arrays January 01 ,2026

Find the Last Elemen...

Count the...
Arrays January 01 ,2026

Count the Number of...

Replace Al...
Arrays January 01 ,2026

Replace All Elements...

Sum of Ele...
Arrays January 01 ,2026

Sum of Elements at E...

Sum of Ele...
Arrays January 01 ,2026

Sum of Elements at O...

Find the A...
Arrays January 01 ,2026

Find the Average of...

Count the...
Arrays January 01 ,2026

Count the Number of...

Remove Dup...
Arrays January 01 ,2026

Remove Duplicate Ele...

Move All Z...
Arrays January 01 ,2026

Move All Zeros to th...

Rotate an...
Arrays January 01 ,2026

Rotate an Array by K...

Rotate an...
Arrays January 01 ,2026

Rotate an Array by O...

Check if T...
Arrays January 01 ,2026

Check if Two Arrays...

Merge Two...
Arrays January 01 ,2026

Merge Two Sorted Arr...

Find Missi...
Arrays January 01 ,2026

Find Missing Number...

Find Dupli...
Arrays January 01 ,2026

Find Duplicate Eleme...

Count Freq...
Arrays January 01 ,2026

Count Frequency of E...

Find the M...
Arrays January 01 ,2026

Find the Majority El...

Find All U...
Arrays January 01 ,2026

Find All Unique Elem...

Insert an...
Arrays January 01 ,2026

Insert an Element at...

Delete an...
Arrays January 01 ,2026

Delete an Element fr...

Find the I...
Arrays January 01 ,2026

Find the Index of an...

Find Union...
Arrays January 01 ,2026

Find Union of Two Ar...

Find Inter...
Arrays January 01 ,2026

Find Intersection of...

Sort an Ar...
Arrays January 01 ,2026

Sort an Array of 0s...

Find the L...
Arrays January 01 ,2026

Find the Largest Sum...

Kadane’s A...
Arrays January 01 ,2026

Kadane’s Algorithm (...

Two Sum Pr...
Arrays January 01 ,2026

Two Sum Problem

Subarray w...
Arrays January 01 ,2026

Subarray with Given...

Longest Su...
Arrays January 01 ,2026

Longest Subarray wit...

Rearrange...
Arrays January 01 ,2026

Rearrange Array Alte...

Leaders in...
Arrays January 01 ,2026

Leaders in an Array

Equilibriu...
Arrays January 01 ,2026

Equilibrium Index of...

Stock Buy...
Arrays January 01 ,2026

Stock Buy and Sell (...

Stock Buy...
Arrays January 01 ,2026

Stock Buy and Sell (...

Sort an Ar...
Arrays January 01 ,2026

Sort an Array of 0s,...

Find All P...
Arrays January 01 ,2026

Find All Pairs with...

Longest Co...
Arrays January 01 ,2026

Longest Consecutive...

Product of...
Arrays January 01 ,2026

Product of Array Exc...

Maximum Pr...
Arrays January 01 ,2026

Maximum Product Suba...

Find the F...
Arrays January 01 ,2026

Find the First Missi...

Count Inve...
Arrays January 01 ,2026

Count Inversions in...

Rearrange...
Arrays January 01 ,2026

Rearrange Array by S...

Check if A...
Arrays January 01 ,2026

Check if Array Can B...

Trapping R...
Arrays January 01 ,2026

Trapping Rain Water

Find Minim...
Arrays January 01 ,2026

Find Minimum in Rota...

Search in...
Arrays January 01 ,2026

Search in Rotated So...

Median of...
Arrays January 01 ,2026

Median of Two Sorted...

Merge Inte...
Arrays January 01 ,2026

Merge Intervals

Count Reve...
Arrays January 01 ,2026

Count Reverse Pairs

Longest Su...
Arrays January 01 ,2026

Longest Subarray wit...

Largest Re...
Arrays January 01 ,2026

Largest Rectangle in...

Maximum Su...
Arrays January 01 ,2026

Maximum Sum Rectangl...

Subarray S...
Arrays January 01 ,2026

Subarray Sum Equals...

Count Dist...
Arrays January 01 ,2026

Count Distinct Eleme...

Sliding Wi...
Arrays January 01 ,2026

Sliding Window Maxim...

Find K Max...
Arrays January 01 ,2026

Find K Maximum Eleme...

Minimum Nu...
Arrays January 01 ,2026

Minimum Number of Ju...

Chocolate...
Arrays January 01 ,2026

Chocolate Distributi...

Find All T...
Arrays January 01 ,2026

Find All Triplets Wi...

Kth Smalle...
Arrays January 01 ,2026

Kth Smallest Element...

Maximum Le...
Arrays January 01 ,2026

Maximum Length Biton...

Find the S...
Arrays February 02 ,2026

Find the Second Larg...

Get In Touch

Kurki bazar Uttar Pradesh

+91-8808946970

techiefreak87@gmail.com