Given an array nums of size n, return the majority element. The majority element is the element that appears more than n / 2 times. You may assume that the majority element always exists in the array.

Constraints:

  • n is between 1 and 50,000.
  • Each element in nums is between -10^9 and 10^9.

Examples:

Example 1:

Input: nums = [3,2,3]
Output: 3

Example 2:

Input: nums = [2,2,1,1,1,2,2]
Output: 2

Solution

Approach: Boyer-Moore Voting Algorithm

This algorithm is specifically designed to find the majority element in an array in linear time and constant space. It works on the principle that if we cancel out each occurrence of an element with all the other elements that are different from it, then the majority element will remain.

  • Initialize: Set count to 0 and candidate to an arbitrary value (or the first element).
  • Iterate through nums:
    • If count is 0, it means the current candidate has been fully 'canceled out' or hasn't been set yet. Assign the current number from nums to candidate.
    • If the current number is the same as candidate, increment count.
    • If the current number is different from candidate, decrement count.
  • Return: The final candidate will be the majority element.

This approach works because the majority element appears more than n/2 times. Even if it gets 'canceled out' multiple times by other elements, its sheer frequency guarantees it will eventually become the candidate again and its count will remain positive until the end.

Time Complexity: O(N) as we iterate through the array once. Space Complexity: O(1) as we only use a few variables.

Python Code Solution

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