Majority Element Moore's Voting Algorithm in DSA Java - Time & Space Complexity
We want to understand how fast the Moore's Voting Algorithm finds the majority element in a list.
How does the time needed grow as the list gets bigger?
Analyze the time complexity of the following code snippet.
public int majorityElement(int[] nums) {
int count = 0, candidate = 0;
for (int num : nums) {
if (count == 0) {
candidate = num;
}
count += (num == candidate) ? 1 : -1;
}
return candidate;
}
This code finds the majority element by tracking a candidate and adjusting a count as it scans the array once.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Single loop through the array elements.
- How many times: Exactly once for each element in the input array.
As the input size grows, the algorithm checks each element once, so the work grows directly with the number of elements.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 checks and updates |
| 100 | About 100 checks and updates |
| 1000 | About 1000 checks and updates |
Pattern observation: The number of operations grows linearly with input size.
Time Complexity: O(n)
This means the time to find the majority element grows in direct proportion to the number of elements.
[X] Wrong: "The algorithm needs to check pairs or do nested loops, so it is slower than linear."
[OK] Correct: The algorithm only scans the list once, updating a count and candidate without nested loops, so it runs in linear time.
Understanding this algorithm shows you can find efficient solutions by clever counting, a skill valued in problem solving and interviews.
"What if we needed to verify the candidate by counting its occurrences after the first pass? How would that affect the time complexity?"
Practice
Solution
Step 1: Understand the problem Moore's Voting Algorithm solves
The algorithm is designed to find the majority element, which is the element that appears more than half the times in the array.Step 2: Compare with other options
Sorting, finding smallest, or reversing are unrelated to the majority element problem.Final Answer:
To find the element that appears more than half the times -> Option AQuick Check:
Majority element = element appearing > n/2 times [OK]
- Confusing majority element with most frequent element
- Thinking it sorts the array
- Assuming it finds smallest or largest element
Solution
Step 1: Check valid initialization for count
Count starts at 1 because the first candidate is chosen and has one vote initially.Step 2: Validate each option
- -1 is invalid as count should not start negative.
- 0 is incorrect because the first candidate is already counted once.
- null is invalid for int type in Java.Final Answer:
int count = 1; -> Option DQuick Check:
Count starts at one for the first candidate [OK]
- Initializing count with 0 instead of 1
- Using null for primitive int
- Starting count negative
int[] arr = {2, 2, 1, 1, 1, 2, 2};
int candidate = arr[0];
int count = 1;
for (int i = 1; i < arr.length; i++) {
if (arr[i] == candidate) count++;
else count--;
if (count == 0) {
candidate = arr[i];
count = 1;
}
}
System.out.println(candidate);Solution
Step 1: Trace the candidate and count changes
Start candidate=2, count=1
i=1: arr[1]=2 equals candidate, count=2
i=2: arr[2]=1 not equal, count=1
i=3: arr[3]=1 not equal, count=0 -> reset candidate=1, count=1
i=4: arr[4]=1 equals candidate, count=2
i=5: arr[5]=2 not equal, count=1
i=6: arr[6]=2 not equal, count=0 -> reset candidate=2, count=1Step 2: Final candidate after loop
Candidate is 2 after last iteration.Final Answer:
2 -> Option AQuick Check:
Final candidate = 2 [OK]
- Not resetting candidate when count hits zero
- Confusing candidate value after last iteration
- Assuming output is the first element
int candidate = 0;
int count = 0;
for (int num : arr) {
if (count == 0) candidate = num;
if (num == candidate) count++;
else count = 0;
}
System.out.println(candidate);Solution
Step 1: Analyze count update logic
Count should decrement when current number is not candidate, but code resets count to 0.Step 2: Effect of resetting count to 0
This causes the algorithm to lose track of votes incorrectly, breaking the logic.Final Answer:
Resetting count to 0 instead of decrementing -> Option CQuick Check:
Count must decrement, not reset to zero [OK]
- Resetting count to zero instead of decrementing
- Misunderstanding candidate update timing
- Confusing loop types as error
Example:
int[] arr = {1, 2, 3, 4, 5, 6};Solution
Step 1: Understand Moore's Voting Algorithm assumption
The algorithm assumes a majority element exists (more than half the array).Step 2: Behavior when no majority element exists
It returns a candidate but this candidate may not actually be majority without a verification step.Step 3: Verification necessity
To confirm majority, a second pass counting candidate occurrences is needed.Final Answer:
The algorithm returns an incorrect candidate without verification -> Option BQuick Check:
No majority means candidate may be wrong [OK]
- Assuming algorithm throws error if no majority
- Thinking it returns null automatically
- Believing it always returns highest frequency element
Ready to prove it?
Pass the test and this pattern moves unknown
