Majority Element - Problem
Given an array nums of size n, find and return the majority element.
The majority element is defined as the element that appears more than โn / 2โ times. In other words, it appears in more than half of the array positions.
Key points:
- You can assume that the majority element always exists in the array
- There is always exactly one majority element
- The majority element appears more than n/2 times, making it the most frequent element
Example: In array [3,2,3], element 3 appears 2 times out of 3 total elements. Since 2 > 3/2 = 1.5, element 3 is the majority element.
Input & Output
example_1.py โ Basic Majority
$
Input:
[3,2,3]
โบ
Output:
3
๐ก Note:
Element 3 appears 2 times out of 3 total elements. Since 2 > 3/2 = 1.5, element 3 is the majority element.
example_2.py โ Larger Array
$
Input:
[2,2,1,1,1,2,2]
โบ
Output:
2
๐ก Note:
Element 2 appears 4 times out of 7 total elements. Since 4 > 7/2 = 3.5, element 2 is the majority element.
example_3.py โ Single Element
$
Input:
[1]
โบ
Output:
1
๐ก Note:
With only one element, it automatically becomes the majority element since 1 > 1/2 = 0.5.
Constraints
- n == nums.length
- 1 โค n โค 5 ร 104
- -109 โค nums[i] โค 109
- Follow-up: Could you solve the problem in linear time and in O(1) space? (Hint: Boyer-Moore Voting Algorithm)
Visualization
Tap to expand
Understanding the Visualization
1
Count Frequencies
Track how many times each element appears in the array
2
Calculate Threshold
Majority threshold is n/2, element must appear more than this
3
Find Winner
Return the element whose count exceeds the majority threshold
Key Takeaway
๐ฏ Key Insight: The majority element appears more than n/2 times, so counting frequencies and comparing against n/2 threshold efficiently identifies the winner.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code