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
Majority Element VisualizationArray: [3, 2, 3, 3, 1, 3] (n=6, threshold=3)Candidate 34 votesWINNER! โœ“Candidate 21 voteCandidate 11 voteMajority Threshold> 3 votesNeed more than n/2Vote Counting Process323313Count: 4Majority Element: 34 votes > 3 threshold
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.
Asked in
Google 23 Amazon 18 Meta 15 Microsoft 12
127.6K Views
High Frequency
~15 min Avg. Time
2.8K 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