Majority Element – CA21
My Thinking and Approach Introduction In this problem, I was given an array and asked to find the majority element. A majority element is the one that appears more than n/2 times in the array. If n...

Source: DEV Community
My Thinking and Approach Introduction In this problem, I was given an array and asked to find the majority element. A majority element is the one that appears more than n/2 times in the array. If no such element exists, we need to return -1. At first, it looked like a simple counting problem, but I learned that there is a more optimized way to solve it. Problem Statement Given an array arr[] Find the element that appears more than n/2 times If no such element exists, return -1 My Initial Approach Initially, I thought of using a frequency count: Use a HashMap Count occurrences of each element Return the element with count > n/2 Drawback Time Complexity: O(n) Space Complexity: O(n) Although this works, it is not the most optimal solution. Optimized Approach (Boyer-Moore Voting Algorithm) To improve efficiency, I used the Boyer-Moore Voting Algorithm, which works in: Time: O(n) Space: O(1) My Approach Step 1: Find Candidate Maintain two variables: candidate count Traverse the array: If