#169

Majority Element

Easy
ArrayHash TableDivide and ConquerSortingCountingHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal solution uses the Boyer-Moore Voting Algorithm, which efficiently finds the majority element in linear time and constant space by maintaining a candidate and a count.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a candidate variable and a count variable.
  2. 2Step 2: Iterate through the array, updating the candidate and count based on the current element.
  3. 3Step 3: Return the candidate as the majority element.
solution.py8 lines
1def majorityElement(nums):
2    count = 0
3    candidate = None
4    for num in nums:
5        if count == 0:
6            candidate = num
7        count += (1 if num == candidate else -1)
8    return candidate

Complexity note: This complexity is achieved because we only make a single pass through the array, and we use constant space for the count and candidate variables.

  • 1The majority element appears more than half the time, which allows us to use counting techniques.
  • 2The Boyer-Moore Voting Algorithm is a powerful method for finding majority elements efficiently.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.