๐ Majority Element (Boyer-Moore Voting Algorithm)
The Majority Element problem is a classic question that tests your understanding of arrays and optimization techniques. It can be solved efficiently using a clever algorithm called the Boyer-Moore ...

Source: DEV Community
The Majority Element problem is a classic question that tests your understanding of arrays and optimization techniques. It can be solved efficiently using a clever algorithm called the Boyer-Moore Voting Algorithm. ๐ Problem Statement Given an array arr[], find the element that appears more than n/2 times. If no such element exists, return -1. ๐ Examples Example 1: Input: [1, 1, 2, 1, 3, 5, 1] Output: 1 Example 2: Input: [7] Output: 7 Example 3: Input: [2, 13] Output: -1 ๐ง Intuition If an element appears more than n/2 times: ๐ It will always dominate the array ๐ It cannot be completely canceled out This idea leads to the Boyer-Moore algorithm. ๐ Approach 1: Brute Force Count frequency of each element Check if any element appears more than n/2 times Time Complexity: O(nยฒ) ๐ Approach 2: Hash Map Use a dictionary to count frequencies Return element with count > n/2 ๐ป Code: ```python id="mj1" def majority_element(arr): freq = {} for num in arr: freq[num] = freq.get(num, 0) + 1 n