← Back to DSA Animator
Majority ElementLC #169EasyBoyer-Moore Voting
Problem

Given an array nums of size n, return the majority element — the element that appears more than ⌊n/2⌋ times. The majority element always exists.

Example 1
Input: nums = [3,2,3]
Output: 3
Constraints: 1≤n≤5×10⁴  |  Majority element always exists  |  O(1) space?
Try Examples
Custom:
Approach
Boyer-Moore Voting Algorithm
Maintain a candidate and count. If count=0, new candidate. If current == candidate → count++. Else → count--. The majority element outlasts all opposition because it appears > n/2 times.
Array
candidate: —
count: 0
Variables
Index i
nums[i]
candidate
count
0
Step Logic
Press ▶ Play or Next Step to begin.
🎉
Ready
0 / 0
Select an example and press Play.
Algorithm
1
Init candidate = null, count = 0
2
If count == 0: new candidate = nums[i]
3
If nums[i] == candidate: count++ (vote for)
4
If nums[i] != candidate: count-- (cancel vote)
Time
O(n)
Space
O(1)
Why It Works

Think of it as elections: each majority vote cancels one minority vote. Since the majority appears more than n/2 times, it can absorb all cancellations from minority elements and still survive with a positive count at the end.