Find Majority Element in Array - Optimal Approach

Find Majority Element in Array - Optimal Approach

Visualization

Algorithm Steps

  1. Given an array arr of size n.
  2. Initialize count = 0 and candidate = None.
  3. Traverse the array:
  4. → If count == 0, set candidate = current element.
  5. → If current element == candidate, increment count, else decrement count.
  6. After the loop, candidate is the majority element.
  7. (Optional: Verify candidate by counting its actual occurrences if required.)

Find Majority Element in Array using Boyer-Moore Voting Algorithm Code

Python
JavaScript
Java
C++
C
def majority_element(arr):
    count = 0
    candidate = None

    for num in arr:
        if count == 0:
            candidate = num
        count += (1 if num == candidate else -1)

    return candidate

# Sample Input
arr = [2, 2, 1, 1, 1, 2, 2]
print("Majority Element:", majority_element(arr))