Find the Element Appearing More Than Half the Time
Solve this Problemnums of size n, return the majority element — the value that appears MORE THAN ⌊n/2⌋ times. It's guaranteed that a majority element always exists.
Counting each candidate's occurrences by rescanning the array works, but it repeats a lot of counting across candidates. The Boyer-Moore Voting AlgorithmBoyer-Moore Voting AlgorithmA single-pass technique for finding a majority element: treat every element as casting a vote for or against a running candidate, and whenever the vote count hits zero, adopt the next element as the new candidate. Because a true majority element can never be fully outvoted, whatever candidate survives to the end is the answer. answers this in one O(n) pass with O(1) space, by treating the scan as an election that the majority element can never lose.
Test Case 1:
Test Case 2:
Test Case 3:
Constraints
- ◆
1 ≤ nums.length ≤ 5 × 10⁴ - ◆
-2³¹ ≤ nums[i] ≤ 2³¹ - 1 - ◆
It is guaranteed nums always has a majority element.
Try the Dry Run
Don't just read the solution — watch it execute, one step at a time.
| 1 | class Solution { |
| 2 | public int majorityElement(int[] nums) { |
| 3 | int candidate = nums[0], count = 0; |
| 4 | for (int num : nums) { |
| 5 | if (count == 0) { |
| 6 | candidate = num; |
| 7 | } |
| 8 | count += (num == candidate) ? 1 : -1; |
| 9 | } |
| 10 | return candidate; |
| 11 | } |
| 12 | } |
| 13 |
20Start with candidate = nums[0] = 2 and count = 0.
Approach & Solutions
Brute Force
BruteFor each candidate index, scan the entire array counting how many times that value occurs. As soon as a count exceeds half the array's length, that value is the answer. Correct, but every candidate re-scans the whole array from scratch.
O(n²)O(1)1class Solution {
2 public int majorityElement(int[] nums) {
3 for (int i = 0; i < nums.length; i++) {
4 int count = 0;
5 for (int j = 0; j < nums.length; j++) {
6 if (nums[j] == nums[i]) count++;
7 }
8 if (count > nums.length / 2) return nums[i];
9 }
10 return -1;
11 }
12}Optimal — Boyer-Moore Voting Algorithm
OptimalWalk the array once, keeping a candidate and a vote count. Every element that matches the candidate casts a vote for it; every element that doesn't casts a vote against it. If the count ever drops to 0, the current candidate has been fully cancelled out — adopt whatever element comes next as the new candidate. Since the true majority element appears more than half the time, the votes against it (cast by every other value combined) can never fully cancel it out — whichever candidate survives to the end must be it.
O(n)O(1)1class Solution {
2 public int majorityElement(int[] nums) {
3 int candidate = nums[0], count = 0;
4 for (int num : nums) {
5 if (count == 0) {
6 candidate = num;
7 }
8 count += (num == candidate) ? 1 : -1;
9 }
10 return candidate;
11 }
12}