Skip to content
Closed
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions data_structures/arrays/majority_element.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
"""
PROBLEM : Find majority element in the given array.
PROBLEM DESCRIPTION :
Given a array of elements of size n.
The majority element is the element that appears more than [n/2] times.
We assume that the majority element is always exists in the array.
EXAMPLE :
input : array = [1,3,5,1,1]
output : 1
explanation : 1 appears three times in array,
which is greater than [n/2] i.e [5/2] = 2.
APPROACH:
- In an array of elements of size n,
there exists only one element that appears greater than [n/2] times.
- If we sort the given elements in the array the [n/2]th
element in the array must be the majority element.
- if we sort [1,3,5,1,1] it will be [1,1,1,3,5]
element present in the [n/2] index of the sorted array
is majority element i.e 1 where n is size of array.
"""

# function to find majority element
def majority_element(array: list) -> int:

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As there is no test file in this pull request nor any test function or class in the file data_structures/arrays/majority_element.py, please provide doctest for the function majority_element

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As there is no test file in this pull request nor any test function or class in the file data_structures/arrays/majority_element.py, please provide doctest for the function majority_element

"""
Return majority element in the list.
"""
array.sort()
return array[len(array) // 2]


if __name__ == "__main__":
import doctest
doctest.testmod()