DEV Community

Sri Mahalakshmi
Sri Mahalakshmi

Posted on

Finding Majority Element Using Boyer-Moore Voting Algorithm in Python

Problem Explanation

You are given an array arr[].
Your task is to find the majority element.

A majority element is an element that appears more than n/2 times in the array.

If no such element exists, return -1.

Example:

  • Input: arr = [1, 1, 2, 1, 3, 5, 1]
    Output: 1

  • Input: arr = [7]
    Output: 7


Method Used: Boyer-Moore Voting Algorithm

Idea

  • Assume a candidate
  • Increase count if same element appears
  • Decrease count if different element appears
  • Final candidate may be the majority

Why This Method?

  • Time complexity: O(n)
  • Space complexity: O(1)
  • Most optimal solution
  • No extra memory required

Python Code with Explanation

class Solution:
    def majorityElement(self, arr):
Enter fullscreen mode Exit fullscreen mode

Defines the function.


        candidate = None
        count = 0
Enter fullscreen mode Exit fullscreen mode

Initialize:

  • candidate → potential majority element
  • count → tracking frequency

        for num in arr:
Enter fullscreen mode Exit fullscreen mode

Loop through the array.


            if count == 0:
                candidate = num
Enter fullscreen mode Exit fullscreen mode

If count becomes 0, pick a new candidate.


            if num == candidate:
                count += 1
Enter fullscreen mode Exit fullscreen mode

If current element matches candidate, increase count.


            else:
                count -= 1
Enter fullscreen mode Exit fullscreen mode

If different, decrease count.


Verification Step (Important)

        if arr.count(candidate) > len(arr) // 2:
            return candidate
Enter fullscreen mode Exit fullscreen mode

Check if candidate is actually majority.


        return -1
Enter fullscreen mode Exit fullscreen mode

If not majority, return -1.


Complete Code

class Solution:
    def majorityElement(self, arr):
        candidate = None
        count = 0

        for num in arr:
            if count == 0:
                candidate = num

            if num == candidate:
                count += 1
            else:
                count -= 1

        if arr.count(candidate) > len(arr) // 2:
            return candidate

        return -1
Enter fullscreen mode Exit fullscreen mode

Step-by-Step Example

Input:

[1, 1, 2, 1, 3, 5, 1]
Enter fullscreen mode Exit fullscreen mode

Process:

  • Track candidate and count
  • Final candidate = 1
  • Verify → appears more than n/2

Output:

1
Enter fullscreen mode Exit fullscreen mode

Key Takeaway

Boyer-Moore Voting Algorithm efficiently finds the majority element using constant space and a single pass.


Top comments (0)