Majority Element

Easy
Code
Loading editor...
Tap Analyze to see visualization
Variables

Run code to see variables

Output

Console output will appear here

Press Space to start to step? all shortcuts

Solution Guide: Majority Element

Approach

Use Boyer-Moore Voting: maintain a candidate and a count. When count drops to zero, adopt the current element as the new candidate. Increment count for matches, decrement for mismatches. The majority element always survives as the final candidate.

Complexity Analysis

Time
O(n)
Space
O(1)

Pattern

Boyer-Moore Voting

Why It Works

The majority element appears more than n/2 times. Every time it is "cancelled" by a different element, at most one copy is lost. Since it has more copies than all others combined, it always remains as the last candidate standing.

Updated Feb 2026