Given an array nums of size n, return the majority element. The majority element is the element that appears more than n / 2 times. You may assume that the majority element always exists in the array.
Constraints:
nis between1and50,000.- Each element in
numsis between-10^9and10^9.
Examples:
Example 1:
Input: nums = [3,2,3]
Output: 3
Example 2:
Input: nums = [2,2,1,1,1,2,2]
Output: 2
Solution
Approach: Boyer-Moore Voting Algorithm
This algorithm is specifically designed to find the majority element in an array in linear time and constant space. It works on the principle that if we cancel out each occurrence of an element with all the other elements that are different from it, then the majority element will remain.
- Initialize: Set
countto0andcandidateto an arbitrary value (or the first element). - Iterate through
nums:- If
countis0, it means the currentcandidatehas been fully 'canceled out' or hasn't been set yet. Assign the current number fromnumstocandidate. - If the current number is the same as
candidate, incrementcount. - If the current number is different from
candidate, decrementcount.
- If
- Return: The final
candidatewill be the majority element.
This approach works because the majority element appears more than n/2 times. Even if it gets 'canceled out' multiple times by other elements, its sheer frequency guarantees it will eventually become the candidate again and its count will remain positive until the end.
Time Complexity: O(N) as we iterate through the array once. Space Complexity: O(1) as we only use a few variables.
Python Code Solution
class Solution:
def majorityElement(self, nums: list[int]) -> int:
count = 0
candidate = 0
for num in nums:
if count == 0:
candidate = num
if num == candidate:
count += 1
else:
count -= 1
return candidate