Find the Majority Element I

Problem Description

Solution Explanation

Important

The Boyer Moore majority vote algorithm states that if an element appears more than half the time in a list, you can find it in a single pass by letting different elements repeatedly pair up and cancel each other out, leaving the majority element as the sole survivor.

Pasted image 20260708080826.png

Implementation

class Solution:

    def majorityElement(self, nums: List[int]) -> int:

        res, count = 0, 0 # we initialize the result, count

        for n in nums:

            if count == 0: # If the count becomes 0 we change the result

                res = n

            count += (1 if n == res else -1) 
            # increment only if n is the same as res 

        return res