Majority Element - Problem
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 & Output
Example 1 — Basic Case
$
Input:
nums = [3,2,3]
›
Output:
3
💡 Note:
Element 3 appears 2 times, which is more than ⌊3/2⌋ = 1, so 3 is the majority element
Example 2 — Larger Array
$
Input:
nums = [2,2,1,1,1,2,2]
›
Output:
2
💡 Note:
Element 2 appears 4 times, which is more than ⌊7/2⌋ = 3, so 2 is the majority element
Example 3 — Single Element
$
Input:
nums = [1]
›
Output:
1
💡 Note:
Only one element exists, so it's automatically the majority element
Constraints
- n == nums.length
- 1 ≤ n ≤ 5 × 104
- -109 ≤ nums[i] ≤ 109
Visualization
Tap to expand
Understanding the Visualization
1
Input Array
Array with one element appearing > n/2 times
2
Count Frequencies
Count how many times each element appears
3
Find Majority
Return element with count > ⌊n/2⌋
Key Takeaway
🎯 Key Insight: The majority element appears more than half the time, so it will always survive when other elements cancel out
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code