Challenge - 5 Problems
Moore's Voting Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of Moore's Voting Algorithm on a given list
What is the output of the following Python code that implements Moore's Voting Algorithm to find the majority element?
DSA Python
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]))
Attempts:
2 left
💡 Hint
The majority element is the one that appears more than half the time.
✗ Incorrect
The algorithm picks candidate 2 and confirms it as majority because it appears 4 times out of 7.
🧠 Conceptual
intermediate1:30remaining
Understanding the count variable in Moore's Voting Algorithm
In Moore's Voting Algorithm, what does the variable 'count' represent during the iteration over the list?
Attempts:
2 left
💡 Hint
Think about how the algorithm balances the candidate count.
✗ Incorrect
Count increases when the current element matches the candidate and decreases otherwise, tracking net support.
❓ Predict Output
advanced2:00remaining
Output when no majority element exists
What will the following code output when run on a list with no majority element?
DSA Python
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([1, 2, 3, 4]))
Attempts:
2 left
💡 Hint
Trace the algorithm step by step to see the final candidate.
✗ Incorrect
The candidate ends as 3 after the last iteration, but it is not a true majority.
🔧 Debug
advanced1:30remaining
Identify the error in this Moore's Voting Algorithm implementation
What error will this code produce when run?
DSA Python
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([3,3,4,2,4,4,2,4,4]))
Attempts:
2 left
💡 Hint
Check the if condition syntax carefully.
✗ Incorrect
The code uses '=' instead of '==' in the if condition, causing a SyntaxError.
🧠 Conceptual
expert2:00remaining
Why Moore's Voting Algorithm requires a second pass in some cases
Why might Moore's Voting Algorithm require a second pass over the list after finding a candidate?
Attempts:
2 left
💡 Hint
The algorithm assumes a majority element exists but does not confirm it.
✗ Incorrect
The first pass finds a candidate, but the second pass confirms if it truly is the majority.