← Back to Leo Academy Masterclass

Problem #169: Majority Element

Easy Array & String

Intuition & Strategy Breakdown

Use Boyer-Moore Voting Algorithm. Maintain candidate and count; increment count for matching element, decrement for different, updating candidate when count drops to zero.

Python Solution

class Solution:
    def majorityElement(self, nums: list[int]) -> int:
        res, count = 0, 0
        for n in nums:
            if count == 0:
                res = n
            count += (1 if n == res else -1)
        return res

Java Solution

class Solution {
    public int majorityElement(int[] nums) {
        int count = 0, candidate = 0;
        for (int num : nums) {
            if (count == 0) {
                candidate = num;
            }
            count += (num == candidate) ? 1 : -1;
        }
        return candidate;
    }
}
Watch Interactive Video on Leo Academy Main App