[Geeks for Geeks] Majority Element

Majority Element

Given an array A of N elements. Find the majority element in the array. A majority element in an array A of size N is an element that appears more than N/2 times in the array.

  • Time : O(n)
  • Space : O(1)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
int majorityElement(int a[], int size) {
int res = -1, count = 0;
for(int i = 0; i < size; i++) {
if(a[i] == res) count++;
else if(count == 0) {
count++;
res = a[i];
} else count--;
}
count = 0;
for(int i = 0; i < size; i++) {
if(a[i] == res) count++;
}

return count * 2 > size ? res : -1;
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/21/PS/GeeksforGeeks/majority-element/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.