algoadvance

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.

Example:

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

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

Clarifying Questions:

  1. Q: Can the array be empty?
    A: No, you may assume that the array is non-empty and a majority element always exists.

  2. Q: Is the array always of integer type?
    A: Yes, the array is always comprised of integers.

  3. Q: Are there any constraints on the input size?
    A: The problem doesn’t specify constraints but typical constraints can be expected like n <= 10^5.

Strategy:

We’ll use the Boyer-Moore Voting Algorithm for this problem due to its efficiency. The algorithm works in two phases:

  1. Finding a Candidate: We iterate through the array and maintain a count of the potential candidate for the majority element.
  2. Verification (optional in this context): Since the problem states that a majority element always exists, this step can generally be skipped. However, let’s mention how it would work for completeness: in this step, we’d confirm if the candidate is actually the majority element by counting its occurrences.

Boyer-Moore Voting Algorithm:

Code:

Here’s the implementation of the Boyer-Moore Voting Algorithm in Python:

def majorityElement(nums):
    candidate = None
    count = 0

    for num in nums:
        if count == 0:
            candidate = num
            count = 1
        elif num == candidate:
            count += 1
        else:
            count -= 1

    return candidate

Time Complexity:

This provides an efficient and effective solution to finding the majority element in the array.

Try our interview co-pilot at AlgoAdvance.com