1
1
"""
2
2
PROBLEM : Find majority element in the given array.
3
-
4
3
PROBLEM DESCRIPTION :
5
4
Given a array of elements of size n.
6
5
The majority element is the element that appears more than [n/2] times.
7
6
We assume that the majority element is always exists in the array.
8
-
9
7
EXAMPLE :
10
8
input : array = [1,3,5,1,1]
11
9
output : 1
12
- explanation : 1 appears three times in array which is greater than [n/2] i.e [5/2] = 2.
13
-
10
+ explanation : 1 appears three times in array,
11
+ which is greater than [n/2] i.e [5/2] = 2.
14
12
APPROACH:
15
- - In an array of elements of size n there exists only one element that appears greater than [n/2] times.
16
-
17
- - If we sort the given elements in the array the [n/2] element in the array must be the majority element.
18
- if we sort [1,3,5,1,1] it will be [1,1,1,3,5]
19
- element present in the [n/2] index of the sorted array is majority element i.e 1 where n is size of array.
13
+ - In an array of elements of size n,
14
+ there exists only one element that appears greater than [n/2] times.
15
+ - If we sort the given elements in the array the [n/2]th
16
+ element in the array must be the majority element.
17
+ - if we sort [1,3,5,1,1] it will be [1,1,1,3,5]
18
+ element present in the [n/2] index of the sorted array
19
+ is majority element i.e 1 where n is size of array.
20
20
"""
21
21
22
-
23
22
# function to find majority element
24
23
def majority_element (array : list ) -> int :
25
24
"""
@@ -31,5 +30,4 @@ def majority_element(array: list) -> int:
31
30
32
31
if __name__ == "__main__" :
33
32
import doctest
34
-
35
33
doctest .testmod ()
0 commit comments