Given a list of integers, return the majority element (the element that appears more than ⌊n / 2⌋ times).
Please solve using the most optimal algorithm possible.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
The most optimal algorithm for finding the majority element is the Boyer-Moore Voting Algorithm. It runs in O(n) time and O(1) space.
Boyer-Moore Voting Algorithm
python
def findMajorityElement(nums):
# Phase 1: Find a candidate
candidate = None
count = 0
for num in nums:
if count == 0:
candidate = num
count = 1
elif num == candidate:
count += 1
else:
count -= 1
# Phase 2: Verify the candidate (optional if guaranteed to have majority)
# If the problem guarantees a majority element exists, you can skip this
count = sum(1 for num in nums if num == candidate)
if count > len(nums) // 2:
return candidate
else:
return None # No majority element
How It Works
Candidate Selection Phase:
Maintain a candidate and a count
If count is 0, set current element as new candidate
If current element equals candidate, increment count
Otherwise, decrement count
Key Insight: The majority element will always survive because it appears more than n/2 times. Even if all other elements "vote against" it, there aren't enough of them to eliminate it.
Example Walkthrough
For array [2, 2, 1, 1, 1, 2, 2]:
Start: candidate = None, count = 0
See 2: candidate = 2, count = 1
See 2: candidate = 2, count = 2
See 1: candidate = 2, count = 1
See 1: candidate = 2, count = 0
See 1: candidate = 1, count = 1
See 2: candidate = 1, count = 0
See 2: candidate = 2, count = 1
Result: candidate = 2
Why It's Optimal
Time: O(n) - single pass (or two if verification needed)