Majority Element II

Solution Code
class Solution:
    def majorityElement(self, nums: List[int]) -> List[int]:
        # Phase 1: Find candidates
        cand1, cand2 = None, None
        count1, count2 = 0, 0
        
        for n in nums:
            if cand1 == n:
                count1 += 1
            elif cand2 == n:
                count2 += 1
            elif count1 == 0:
                cand1, count1 = n, 1
            elif count2 == 0:
                cand2, count2 = n, 1
            else:
                count1 -= 1
                count2 -= 1
                
        # Phase 2: Verify candidates
        result = []
        if nums.count(cand1) > len(nums) // 3:
            result.append(cand1)
        if nums.count(cand2) > len(nums) // 3:
            result.append(cand2)
            
        return result
Video GuideLeetcode Daily

Time Complexity

O(N)

Space Complexity

O(1)