
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 ): Defines the function. candidate = None count = 0 Initialize: candidate → potential majority element count → tracking frequency for num in arr : Loop through the array. if count == 0 : candidate = num If count becomes 0, pick a new candidate. if num == candidate : count += 1 If current element matches candidate, increase count.
Continue reading on Dev.to Python
Opens in a new tab


