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.
Input: nums = [3,2,3]
Output: 3
Input: nums = [2,2,1,1,1,2,2]
Output: 2
Q: Can the array be empty?
A: No, you may assume that the array is non-empty and a majority element always exists.
Q: Is the array always of integer type?
A: Yes, the array is always comprised of integers.
Q: Are there any constraints on the input size?
A: The problem doesn’t specify constraints but typical constraints can be expected like n <= 10^5
.
We’ll use the Boyer-Moore Voting Algorithm for this problem due to its efficiency. The algorithm works in two phases:
None
and a count
as 0
.count
is 0
, set candidate
to the current element.candidate
, increment count
.candidate
, decrement count
.Here’s the implementation of the Boyer-Moore Voting Algorithm in Python:
def majorityElement(nums):
candidate = None
count = 0
for num in nums:
if count == 0:
candidate = num
count = 1
elif num == candidate:
count += 1
else:
count -= 1
return candidate
n
is the number of elements in the array. We only pass through the list once.This provides an efficient and effective solution to finding the majority element in the array.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?