Majority Element Moore's Voting Algorithm in DSA Javascript - Time & Space Complexity
We want to understand how fast 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.
function majorityElement(nums) {
let count = 0;
let candidate = null;
for (const num of 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 list once.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: One loop that goes through each number in the list exactly once.
- How many times: The loop runs once for every element in the list (n times).
As the list grows, the number of steps grows directly with it.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 steps |
| 100 | About 100 steps |
| 1000 | About 1000 steps |
Pattern observation: The steps increase in a straight line as the list gets bigger.
Time Complexity: O(n)
This means the time to find the majority element grows directly with the size of the list.
[X] Wrong: "The algorithm checks every pair of elements, so it must be O(n²)."
[OK] Correct: The algorithm only scans the list once, updating counts without nested loops, so it runs in linear time.
Knowing this algorithm's time complexity helps you explain efficient solutions clearly and confidently in interviews.
"What if we added a second loop to verify the candidate's count? How would the time complexity change?"
Practice
Solution
Step 1: Understand the problem Moore's Voting Algorithm solves
It 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 majority element detection.Final Answer:
To find the element that appears more than half the time -> 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: Identify correct variable initialization
Moore's Voting Algorithm starts with count = 0 and candidate = null (or undefined) to indicate no candidate chosen yet.Step 2: Check other options for correctness
Options A, C, and D initialize count or candidate incorrectly, which can cause logic errors.Final Answer:
let count = 0, candidate = null; -> Option BQuick Check:
Initialize count=0 and candidate=null [OK]
- Starting count at 1 instead of 0
- Assigning candidate a number before selection
- Swapping count and candidate initialization
function majorityElement(nums) {
let count = 0, candidate = null;
for (const num of nums) {
if (count === 0) candidate = num;
count += (num === candidate) ? 1 : -1;
}
return candidate;
}
console.log(majorityElement([2,2,1,1,1,2,2]));Solution
Step 1: Trace the loop and candidate updates
Initial count=0, candidate=null. Iteration updates candidate and count as follows:
- num=2: count=0, candidate=2, count=1
- num=2: count=1, same candidate, count=2
- num=1: count=2, different candidate, count=1
- num=1: count=1, different candidate, count=0
- num=1: count=0, candidate=1, count=1
- num=2: count=1, different candidate, count=0
- num=2: count=0, candidate=2, count=1Step 2: Final candidate after loop
The candidate is 2 after the loop ends, which is the majority element.Final Answer:
2 -> Option DQuick Check:
Majority element found = 2 [OK]
- Assuming candidate never changes
- Confusing count increments and decrements
- Returning count instead of candidate
function majorityElement(nums) {
let count = 1, candidate = nums[0];
for (let i = 1; i < nums.length; i++) {
if (nums[i] === candidate) {
count++;
} else {
count--;
if (count === 0) {
candidate = nums[i];
count = 1;
}
}
}
return candidate;
}Solution
Step 1: Analyze initialization and loop
Starting count at 1 and candidate as nums[0] is a valid approach. Loop starts at i=1 to compare remaining elements.Step 2: Check logic inside loop
Count increments if current equals candidate, else decrements. When count hits zero, candidate updates and count resets to 1. This matches Moore's Voting Algorithm logic.Final Answer:
No bug, code is correct -> Option CQuick Check:
Initialization and loop logic correct [OK]
- Thinking count must start at 0
- Assuming candidate must be null initially
- Starting loop at wrong index
Example:
[1, 2, 3, 4]Solution
Step 1: Understand Moore's Voting Algorithm assumption
The algorithm assumes a majority element exists (appears more than half the time). If none exists, it still returns a candidate but it may not be a true majority.Step 2: Analyze example array [1, 2, 3, 4]
No element appears more than 2 times (half of 4). The algorithm will return a candidate but it is not a valid majority element.Final Answer:
An incorrect majority element -> Option AQuick Check:
No majority means algorithm returns wrong candidate [OK]
- Assuming algorithm returns null if no majority
- Thinking it returns highest frequency element always
- Believing it returns first element by default
Ready to prove it?
Pass the test and this pattern moves unknown
