Majority Element in Java(LeetCode 169): Arrays
If you ask someone how to find the most common number in an array, they will almost always say "count everything with a HashMap." That is a fine answer, and it works. But LeetCode 169 (Majority Element) gives you a special guarantee that lets you do much better: the answer appears more than half the time. Because of that one detail, you can solve it with just two variables and a single loop, using no extra memory at all.
In this post I'll explain the idea behind it (it's called the Boyer-Moore voting algorithm), trace it by hand on a small array, and then show the Java code I used in my video. There is also a small step-by-step simulator below, so you can type in your own array and watch the candidate and the counter change.
Video Walkthrough
If you'd rather watch than read, the full explanation is here:
1. What the Problem Asks
You get an integer array nums of size n. Return the majority element, which is the value that shows up more than n / 2 times. The problem promises that such a value always exists, so you never have to handle the "no answer" case.
- "More than half" is strict. In an array of 6 numbers, the winner has to appear at least 4 times, not 3.
- Since the majority element is guaranteed to exist, we never need a second pass to confirm it.
- There can only ever be one majority element. Two different values cannot both have more than half of the slots.
The Core Idea: Votes Cancel Each Other Out
Think of the array as an election. Keep one candidate and one count. Walk through the numbers one by one:
- If the count is
0, nobody is leading right now, so the current number becomes the new candidate. - If the current number equals the candidate, that's a vote for them, so the count goes up.
- If it's a different number, it cancels one vote, so the count goes down.
Why does this land on the right answer? Every time a different number cancels a vote, you are removing a pair of unequal elements. The majority element owns more than half of the array, so even if every other number teamed up against it, there would still be some copies of it left standing at the end. Whoever survives in the candidate variable is that element.
candidate = nums[i] pick a new leader
c++ add a vote
c-- cancel a vote
The candidate switches to 1 at index 4 and back to 2 at index 6. The final candidate, 2, is the majority element.
Quick Examples
Output: 3
Why: 3 appears twice out of three, which is more than half. The lone 2 cancels one 3, and a 3 is still left.
Output: 2
Why: 2 appears four times out of seven. The three 1s can cancel at most three 2s, so one 2 always survives.
2. Interactive Voting Simulator
Type your own numbers (separated by commas) or pick a preset, then click through the array one element at a time. Watch when the count hits zero and the candidate changes.
3. Step-by-Step Code Walkthrough
Here is what the Java code does, in plain order:
- Set up two variables:
cis the running count andcandidateis the number we currently believe is the winner. Both start at0. - Loop through the array once: for each element we first check whether the count has dropped to zero.
- Pick a new candidate when needed: if
c == 0, we setcandidate = nums[i]. Whatever we had before has been fully cancelled out. - Vote or cancel: if
nums[i]equals the candidate we doc++, otherwise we doc--. - Return the candidate: because a majority element is guaranteed, the value left in
candidateafter the loop is the answer.
The Java Solution
class Solution {
public int majorityElement(int[] nums) {
int c = 0, candidate = 0;
for (int i = 0; i < nums.length; i++) {
if (c == 0) {
candidate = nums[i];
}
if (candidate == nums[i]) {
c++;
} else {
c--;
}
}
return candidate;
}
}
Test It Locally
Paste this Main class into your IDE to try a few inputs, including an array with a single element:
public class Main {
public static int majorityElement(int[] nums) {
int c = 0, candidate = 0;
for (int i = 0; i < nums.length; i++) {
if (c == 0) {
candidate = nums[i];
}
if (candidate == nums[i]) {
c++;
} else {
c--;
}
}
return candidate;
}
public static void main(String[] args) {
System.out.println(majorityElement(new int[]{3, 2, 3})); // 3
System.out.println(majorityElement(new int[]{2, 2, 1, 1, 1, 2, 2})); // 2
System.out.println(majorityElement(new int[]{6, 5, 5})); // 5
System.out.println(majorityElement(new int[]{1})); // 1
}
}
Console Output:
2
5
1
4. Complexity Analysis
- Time Complexity:
O(n). The array is scanned exactly once, and every step inside the loop takes constant time. - Space Complexity:
O(1). Only two integer variables are used, no matter how large the array is.
5. Other Approaches & Interview Tips
- HashMap counting: Store each number's frequency and return the one that crosses
n / 2. It is easy to write and stillO(n)time, but it costsO(n)extra space. Interviewers often ask for the follow-up of doing it in constant space, and that's where the voting idea comes in. - Sorting: After sorting, the majority element always sits at index
n / 2, sonums[n / 2]is the answer. The catch is theO(n log n)time. - The guarantee matters: This voting trick only gives a correct result because the problem promises a majority element exists. If that promise were removed, you would need a second loop to count the candidate and confirm it really passes
n / 2. - Common mistake: Don't reset
candidateinside theelsebranch. The candidate only changes when the count has reached zero, at the top of the next iteration. - Related problems to practice:
- LeetCode 229 (Majority Element II): Find everything that appears more than
n / 3times. It extends the same idea to two candidates. - LeetCode 242 (Valid Anagram): Another problem where counting does the job and sorting is not needed.
- LeetCode 229 (Majority Element II): Find everything that appears more than
Comments
Post a Comment