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
Majority Element Problem: [3,2,3,3,6]Input Array:32336Element Frequencies:3 appears 3 times2 appears 1 time6 appears 1 time⌊n/2⌋ = ⌊5/2⌋ = 2, so we need count > 2Result: 3 (appears 3 > 2 times)
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
Asked in
Apple 15 Google 12 Amazon 10 Microsoft 8
411.5K Views
High Frequency
~15 min Avg. Time
15.2K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen