DEV Community

VARUN
VARUN

Posted on

CA 21 - Find the Majority Element



1.Problem Understanding

Given an array.
Find the element that appears more than n/2 times.
If no such element exists → return -1

Example
[1, 1, 2, 1, 3, 5, 1]
Output:
1
Because it appears more than n/2

2.Idea (Understand this or forget it)
Majority element cancels out all other elements.

Same element → increase count
Different element → decrease count
If majority exists → it will survive

Top comments (0)