Majority Element Moore's Voting Algorithm in DSA Python - 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.
def majority_element(nums):
count = 0
candidate = None
for num in nums:
if count == 0:
candidate = num
count += (1 if num == candidate else -1)
return candidate
This code finds the majority element by counting and updating a candidate 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 once.
- How many times: Exactly once for each element, so n times if the list has n elements.
As the list gets bigger, the algorithm checks each number once, so the work grows directly with the list size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 checks |
| 100 | About 100 checks |
| 1000 | About 1000 checks |
Pattern observation: The number of operations grows in a straight line with input size.
Time Complexity: O(n)
This means the time taken grows directly in proportion to the number of elements in the list.
[X] Wrong: "The algorithm checks pairs or does nested loops, so it must be slower than O(n)."
[OK] Correct: The algorithm only scans the list once, updating counts without extra loops inside, so it stays fast and linear.
Knowing this algorithm's time complexity shows you can find efficient solutions that scan data once, a skill valued in many coding challenges.
"What if we added a second pass to verify the candidate's count? How would the time complexity change?"
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 time in the array.Step 2: Compare with other options
Sorting, finding smallest element, or counting unique elements are not the goals of this algorithm.Final Answer:
To find the element that appears more than half the time -> Option AQuick Check:
Majority element = element with >50% frequency [OK]
- Confusing majority element with most frequent element
- Thinking it sorts the array
- Assuming it counts unique elements
Solution
Step 1: Recall initialization in Moore's Voting Algorithm
We start with count = 0 and candidate = None to indicate no candidate chosen yet.Step 2: Check other options for correctness
Starting count at 1 or candidate at 0 without context is incorrect; None is used to indicate no candidate.Final Answer:
count = 0; candidate = None -> Option DQuick Check:
Initialize count=0 and candidate=None [OK]
- Starting count at 1 instead of 0
- Assigning candidate to 0 prematurely
- Using None for count instead of candidate
def majority_element(nums):
count = 0
candidate = None
for num in nums:
if count == 0:
candidate = num
count += (1 if num == candidate else -1)
return candidate
print(majority_element([2,2,1,1,1,2,2]))Solution
Step 1: Trace the candidate and count updates
Start with count=0, candidate=None. Iterate: 2 (count=0->1, candidate=2), 2 (count=2), 1 (count=1), 1 (count=0), 1 (count=1, candidate=1), 2 (count=0), 2 (count=1, candidate=2).Step 2: Final candidate after iteration
The candidate ends as 2 after the loop finishes.Final Answer:
2 -> Option AQuick Check:
Majority element in [2,2,1,1,1,2,2] is 2 [OK]
- Not updating candidate when count is zero
- Confusing candidate with last element
- Assuming candidate is None if count resets
def majority_element(nums):
count = 0
candidate = None
for num in nums:
if count == 0:
candidate = num
if num == candidate:
count += 1
else:
count -= 1
return candidate
print(majority_element([3,3,4]))Solution
Step 1: Analyze candidate update and count logic
Candidate updates when count is zero. Count increments if current num equals candidate, else decrements.Step 2: Test with input [3,3,4]
Iteration: 3 (count=1, candidate=3), 3 (count=2), 4 (count=1). Returns candidate 3 correctly.Final Answer:
No bug, code works correctly -> Option BQuick Check:
Code correctly finds majority element [OK]
- Thinking candidate is not updated when count is zero
- Confusing increment and decrement logic
- Ignoring empty list edge case
Example:
[1,2,3,4]Solution
Step 1: Understand Moore's Voting Algorithm assumption
The algorithm assumes a majority element exists (more than half the array). If none exists, it still returns a candidate but it may be incorrect.Step 2: Apply to example [1,2,3,4]
No element appears more than 2 times (half of 4). The algorithm returns a candidate but it is not a true majority.Final Answer:
None or incorrect candidate -> Option CQuick Check:
No majority means candidate may be wrong [OK]
- Assuming algorithm returns error 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
