Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Find the majority element in an array

Find the element that appears more than half the time using Boyer–Moore Voting Algorithm.

Python practice16 minArrays – Fundamentals & PatternsIntermediateLast updated March 25, 2026

Problem statement

Given a list of integers, find the majority element — an element that appears more than n/2 times in the list. If such an element exists, return it; otherwise return None. Implement an algorithm with O(n) time and O(1) space, and verify the candidate before returning.

Task

Return the majority element (element appearing > n/2 times) if it exists; otherwise return None. Use O(n) time and O(1) extra space.

Examples

Simple majority

Input

majority_element([3, 3, 4])

Output

3

3 appears 2 of 3 times, which is > 3/2, so it's the majority.

Input format

A single list of integers, e.g. [3, 3, 4].

Output format

Return the majority element as an integer if found; otherwise return None (compared as empty output).

Constraints

1 <= len(nums) <= 10^5. Elements are integers. Must run in O(n) time and O(1) extra space.

Samples

Sample 1

Input

[2, 2, 1, 1, 2]

Output

2

2 appears 3 times out of 5, which is > 5/2.