Skip to content

Commit ba76ab1

Browse files
committed
added majority element problem to arrays
1 parent 03a4251 commit ba76ab1

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed
+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
"""
2+
PROBLEM : Find majority element in the given array.
3+
4+
PROBLEM DESCRIPTION :
5+
Given a array of elements of size n.
6+
The majority element is the element that appears more than [n/2] times.
7+
We assume that the majority element is always exists in the array.
8+
9+
EXAMPLE :
10+
input : array = [1,3,5,1,1]
11+
output : 1
12+
explanation : 1 appears three times in array which is greater than [n/2] i.e [5/2] = 2.
13+
14+
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.
20+
"""
21+
22+
23+
#function to find majority element
24+
def majority_element(array:list)->int:
25+
'''
26+
Return majority element in the list.
27+
'''
28+
array.sort()
29+
return array[len(array)//2]
30+
31+
32+
if __name__ == "__main__":
33+
import doctest
34+
doctest.testmod()

0 commit comments

Comments
 (0)