Majority Element in Python

The majority element is an element that appears more than half the times in an array. For example, in an array of size 8, a majority element must appear at least 5 times. Python provides several approaches to find the majority element efficiently.

Problem Definition

Given an array of integers, find the element that appears more than n/2 times, where n is the array size. If no such element exists, return -1.

Example 1 ?

Input: [2, 1, 1, 2, 2, 2]
Output: 2
Explanation: Element 2 appears 4 times out of 6, which is more than 6/2 = 3

Example 2 ?

Input: [1, 2, 3, 4, 5]
Output: -1
Explanation: No element appears more than 5/2 = 2.5 times

Method 1: Using Dictionary (HashMap)

Count the frequency of each element using a dictionary and find the element with frequency greater than n/2 ?

def find_majority_element(arr):
    n = len(arr)
    frequency = {}
    
    # Count frequency of each element
    for num in arr:
        frequency[num] = frequency.get(num, 0) + 1
    
    # Find element with frequency > n/2
    for num, count in frequency.items():
        if count > n // 2:
            return num
    
    return -1

# Test the function
arr = [2, 1, 1, 2, 2, 2]
result = find_majority_element(arr)

if result != -1:
    print(f"Majority Element is: {result}")
else:
    print("No majority element in array")
Majority Element is: 2

Method 2: Using Counter from Collections

Python's Counter class provides a more concise way to count element frequencies ?

from collections import Counter

def find_majority_with_counter(arr):
    n = len(arr)
    counter = Counter(arr)
    
    for num, count in counter.items():
        if count > n // 2:
            return num
    
    return -1

# Test with different arrays
test_arrays = [
    [2, 1, 1, 2, 2, 2],
    [1, 1, 1, 2, 2],
    [1, 2, 3, 4, 5]
]

for arr in test_arrays:
    result = find_majority_with_counter(arr)
    print(f"Array: {arr}")
    print(f"Majority Element: {result if result != -1 else 'None'}")
    print()
Array: [2, 1, 1, 2, 2, 2]
Majority Element: 2

Array: [1, 1, 1, 2, 2]
Majority Element: 1

Array: [1, 2, 3, 4, 5]
Majority Element: None

Method 3: Boyer-Moore Voting Algorithm

An optimized approach with O(1) space complexity. This algorithm works when a majority element is guaranteed to exist ?

def boyer_moore_majority(arr):
    # Phase 1: Find candidate
    candidate = None
    count = 0
    
    for num in arr:
        if count == 0:
            candidate = num
            count = 1
        elif num == candidate:
            count += 1
        else:
            count -= 1
    
    # Phase 2: Verify candidate
    if arr.count(candidate) > len(arr) // 2:
        return candidate
    
    return -1

# Test the algorithm
arr = [2, 1, 1, 2, 2, 2]
result = boyer_moore_majority(arr)
print(f"Majority Element using Boyer-Moore: {result}")
Majority Element using Boyer-Moore: 2

Comparison of Methods

Method Time Complexity Space Complexity Best For
Dictionary O(n) O(n) General case, easy to understand
Counter O(n) O(n) Clean, readable code
Boyer-Moore O(n) O(1) Memory-efficient, guaranteed majority

Complete Example

def find_majority_complete(arr):
    """Find majority element with detailed output"""
    n = len(arr)
    frequency = {}
    
    # Count frequencies
    for num in arr:
        frequency[num] = frequency.get(num, 0) + 1
    
    print(f"Array: {arr}")
    print(f"Frequencies: {frequency}")
    print(f"Required frequency for majority: > {n // 2}")
    
    # Find majority
    for num, count in frequency.items():
        if count > n // 2:
            print(f"Majority element: {num} (appears {count} times)")
            return num
    
    print("No majority element found")
    return -1

# Test with sample data
test_array = [3, 3, 4, 2, 4, 4, 2, 4, 4]
find_majority_complete(test_array)
Array: [3, 3, 4, 2, 4, 4, 2, 4, 4]
Frequencies: {3: 2, 4: 5, 2: 2}
Required frequency for majority: > 4
Majority element: 4 (appears 5 times)

Conclusion

Use the dictionary approach for general cases with clear logic. Choose Boyer-Moore algorithm when memory efficiency is crucial and a majority element is guaranteed to exist.

Updated on: 2026-03-25T15:46:27+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements