KatInterview

229. Majority Element II

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

Method: Extended Boyer-Moore Voting Algorithm

This problem asks for all elements that appear more than ⌊ n/3 ⌋ times. A key insight is that there can be at most two such elements. If there were three distinct elements each appearing more than n/3 times, their combined count would be greater than 3 * (n/3) = n, which is impossible for an array of size n.

Solution

Majority Element II in Python

class Solution:
    def majorityElement(self, nums: List[int]) -> List[int]:
        # At most two elements can appear more than n/3 times.
        # We use an extended Boyer-Moore Voting Algorithm.

        candidate1, candidate2 = None, None
        count1, count2 = 0, 0

        # Pass 1: Find two potential candidates.
        for num in nums:
            if num == candidate1:
                count1 += 1
            elif num == candidate2:
                count2 += 1
            elif count1 == 0:
                candidate1 = num
                count1 = 1
            elif count2 == 0:
                candidate2 = num
                count2 = 1
            else:
                count1 -= 1
                count2 -= 1

        # Pass 2: Verify the candidates.
        result = []
        count1, count2 = 0, 0
        for num in nums:
            if num == candidate1:
                count1 += 1
            elif num == candidate2:
                count2 += 1
        
        n = len(nums)
        if count1 > n / 3:
            result.append(candidate1)
        # The check 'candidate1 != candidate2' is implicitly handled because
        # if they were the same, the first verification pass would only increment
        # count1, leaving count2 as 0.
        if count2 > n / 3:
            result.append(candidate2)

        return result

Majority Element II in Java

class Solution {
    public List<Integer> majorityElement(int[] nums) {
        // There can be at most two majority elements.
        // We use an extended Boyer-Moore Voting Algorithm.
        
        // Using Integer objects allows for null, making the logic cleaner
        // by not needing arbitrary initial values.
        Integer candidate1 = null, candidate2 = null;
        int count1 = 0, count2 = 0;
        
        // Pass 1: Find the two candidates.
        for (int num : nums) {
            if (candidate1 != null && num == candidate1) {
                count1++;
            } else if (candidate2 != null && num == candidate2) {
                count2++;
            } else if (count1 == 0) {
                candidate1 = num;
                count1 = 1;
            } else if (count2 == 0) {
                candidate2 = num;
                count2 = 1;
            } else {
                count1--;
                count2--;
            }
        }
        
        // Pass 2: Verify the candidates.
        List<Integer> result = new ArrayList<>();
        count1 = 0;
        count2 = 0;
        
        for (int num : nums) {
            if (candidate1 != null && num == candidate1) {
                count1++;
            } else if (candidate2 != null && num == candidate2) {
                count2++;
            }
        }
        
        int n = nums.length;
        if (count1 > n / 3) {
            result.add(candidate1);
        }
        if (count2 > n / 3) {
            result.add(candidate2);
        }
        
        return result;
    }
}

Majority Element II in C++

class Solution {
public:
    vector<int> majorityElement(vector<int>& nums) {
        // There can be at most two majority elements.
        // We use an extended Boyer-Moore Voting Algorithm.
        
        // Pass 1: Find the two candidates.
        int candidate1 = 0, candidate2 = 1; // Initialize with arbitrary different values
        int count1 = 0, count2 = 0;
        
        for (int num : nums) {
            if (num == candidate1) {
                count1++;
            } else if (num == candidate2) {
                count2++;
            } else if (count1 == 0) {
                candidate1 = num;
                count1 = 1;
            } else if (count2 == 0) {
                candidate2 = num;
                count2 = 1;
            } else {
                count1--;
                count2--;
            }
        }
        
        // Pass 2: Verify the candidates.
        count1 = 0;
        count2 = 0;
        for (int num : nums) {
            if (num == candidate1) {
                count1++;
            } else if (num == candidate2) {
                count2++;
            }
        }
        
        vector<int> result;
        if (count1 > nums.size() / 3) {
            result.push_back(candidate1);
        }
        if (count2 > nums.size() / 3) {
            result.push_back(candidate2);
        }
        
        return result;
    }
};

Majority Element II in TypeScript

function majorityElement(nums: number[]): number[] {
    // At most two elements can appear more than n/3 times.
    // We use an extended Boyer-Moore Voting Algorithm.

    let candidate1: number | null = null;
    let candidate2: number | null = null;
    let count1 = 0;
    let count2 = 0;

    // Pass 1: Find two potential candidates.
    for (const num of nums) {
        if (num === candidate1) {
            count1++;
        } else if (num === candidate2) {
            count2++;
        } else if (count1 === 0) {
            candidate1 = num;
            count1 = 1;
        } else if (count2 === 0) {
            candidate2 = num;
            count2 = 1;
        } else {
            count1--;
            count2--;
        }
    }

    // Pass 2: Verify the candidates.
    count1 = 0;
    count2 = 0;
    for (const num of nums) {
        if (num === candidate1) {
            count1++;
        } else if (num === candidate2) {
            count2++;
        }
    }

    const result: number[] = [];
    const n = nums.length;
    if (count1 > n / 3) {
        result.push(candidate1!);
    }
    if (count2 > n / 3) {
        result.push(candidate2!);
    }

    return result;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.