Tensorum
LeetCode 169 · Moore Voting

Majority Element

LeetCode 169 · Easy · solution, intuition & step-by-step walkthrough

Vote: same → +1, different → −1, zero → new candidate.

EasyArrayHash TableDivide and ConquerSortingCounting
7 msruntime · beats 88%
21.2 MBmemory · beats 97%
1approach
14accepted runs · last 26 May 2026

This is how I solved Majority Element (LeetCode 169), an easy problem from the Moore Voting pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.

Intuition

Boyer–Moore voting: pair each occurrence of the candidate against a different value and cancel them. The majority element appears more than half the time, so it can't be fully cancelled and is left as the candidate.

Approach

  1. 1

    count = 0, element = None.

  2. 2

    When count is 0, adopt the current number.

  3. 3

    Same number → count++; different → count−−.

  4. 4

    The surviving element is the majority.

How I solved it

Boyer–Moore votingPythonO(n) time · O(1) space
class Solution:
    def majorityElement(self, nums: List[int]) -> int:
        count =0
        element=None
        for num in nums:
            if count==0:
                element=num
                count=1
            elif element==num:
                count+=1
            elif element!=num:
                count-=1
        return element
Loading the step-through…

Majority Element — FAQ

What is the intuition behind Majority Element?

Boyer–Moore voting: pair each occurrence of the candidate against a different value and cancel them. The majority element appears more than half the time, so it can't be fully cancelled and is left as the candidate.

How do you solve Majority Element (LeetCode 169)?

1. count = 0, element = None. 2. When count is 0, adopt the current number. 3. Same number → count++; different → count−−. 4. The surviving element is the majority.

What is the time and space complexity of Majority Element?

Time: O(n). Space: O(1). (Accepted approach: Boyer–Moore voting.)

What are common mistakes in Majority Element?

This relies on a majority being guaranteed — otherwise verify with a second pass.