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 - Boyer-Moore Voting Algorithm INPUT Array nums (n=3) 3 idx 0 2 idx 1 3 idx 2 Majority Threshold n/2 = 3/2 = 1 Input: nums = [3, 2, 3] 3 appears 2 times 2 appears 1 time 2 > 1 (threshold) ALGORITHM STEPS 1 Initialize candidate=3, count=1 First elem becomes candidate 2 Process nums[1]=2 2 != 3, count-- (count=0) Different: decrement count 3 Process nums[2]=3 count=0, new candidate=3 count=0: set new candidate 4 Increment count count++ (count=1) Final: candidate=3 Return 3 as majority FINAL RESULT Majority Element Found 3 Verification 3 appears 2 times 2 > floor(3/2) = 1 Output: 3 OK - CORRECT Key Insight: Boyer-Moore Voting Algorithm works by maintaining a candidate and count. When we see the same element, we increment count; different element decrements it. If count reaches 0, we pick a new candidate. Time: O(n) | Space: O(1) - The majority element will always survive the "voting" process! TutorialsPoint - Majority Element | Boyer-Moore Voting Algorithm
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